通过DBRef数组查找文档 [英] Finding documents by array of DBRefs
问题描述
解决方案可能正盯着我,但我没有找到任何运气.我的问题是我需要查找包含指定DBRef的所有文档.这是要搜索的集合的结构:
The solution is probably staring me in the face, but I haven't had any luck in finding it. My problem is that I need to find all documents which contain specified DBRef. Here's the structure of the collection to be searched:
{
"_id" : ObjectId("4e2d4892580fd602eb000003"),
"date_added" : ISODate("2011-07-25T11:42:26.395Z"),
"date_updated" : ISODate("2011-07-25T11:43:09.870Z"),
...
"a_list_of_dbrefs" : [
{
"$ref" : "somecollection"
"$id" : "4e2d48ab580fd602eb000004"
}
],
...
"name" : "some name"
}
我需要能够基于出现在a_list_of_dbrefs
中的DBRef检索一组文档(有些a_list_of_dbrefs
可能不包含DBRef,有些可能包含1,有些可能包含多个).
I need to be able to retrieve a set of documents based on a DBRef appearing in a_list_of_dbrefs
(some a_list_of_dbrefs
may contain no DBRefs, others may contain 1, and others may contain more than 1).
这是如何完成的?
推荐答案
我建议转储DBRef
,而假定您知道所引用集合的名称,而只需简单地存储所引用文档的_id
即可.
I'd recommend dumping the DBRef
s in favor of simply storing the _id
of the referenced document assuming you know the name of the collection being referenced.
在MongoDB上,绝对没有办法从服务器端(一步)解析"一个DBRef
数组,并且需要您遍历客户端上的数组并分别解析每个文档.
There is absolutely no way to "resolve" an array of DBRef
from the server-side (in a single step) on MongoDB and requires that you loop through the array on the client and individually resolve each document.
相反,如果您存储的只是引用的_id
数组,则可以检索该数组,然后使用$in
查询将其全部获取.
Conversely, if you store an array of just the referenced _id
you can retrieve that array and then use the $in
query to fetch them all.
因此,您的文档可能会变成这样:
So your document might change to look like this:
{
"_id" : ObjectId("4e2d4892580fd602eb000003"),
"date_added" : ISODate("2011-07-25T11:42:26.395Z"),
"date_updated" : ISODate("2011-07-25T11:43:09.870Z"),
...
"references": [
ObjectId(123), ObjectId(234), ObjectId(567), ObjectId(891)
],
...
"name" : "some name"
}
然后您可以使用references
字段的内容查询MongoDB:
You can then query MongoDB using the contents of the references
field:
db.somecollection.find({"_id": {"$in": references}})
这篇关于通过DBRef数组查找文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!