Finding documents by array of DBRefs

送分小仙女□ 提交于 2019-12-03 12:43:33

I'd recommend dumping the DBRefs in favor of simply storing the _id of the referenced document assuming you know the name of the collection being referenced.

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.

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"
}

You can then query MongoDB using the contents of the references field:

db.somecollection.find({"_id": {"$in": references}})

Try this one, it worked for me:

db.<your collection>.find({"a_list_of_dbrefs.$id": ObjectID("4e2d48ab580fd602eb000004")})

You can also retrieve all elements which has the ref to collection:

db.<your collection>.find({"a_list_of_dbrefs.$ref": "somecollection"})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!