I have following documents in my db
> db.person.find()
{ "_id" : ObjectId("1122"), "name" : "Alice", "age" : 20 }
{ "_id" : ObjectId("3344"), "name" : "Bob", "age" : 21 }
> db.article.find()
{ "_id" : ObjectId("aaaa"), "authors" : [ { "$ref" : "person", "$id" : "1122" } ] }
{ "_id" : ObjectId("bbbb"), "authors" : [ {
"$ref" : "person",
"$id" : "1122"
}, {
"$ref" : "person",
"$id" : "3344"
} ] }
and this is the code I've tried to find articles whose authors contain Bob
import pymongo
import bson.objectid
db = pymongo.MongoClient()['test']
bob_id = bson.objectid.ObjectId('3344')
article = db.article.find_one({ 'authors': { '$in': [ bob_id ] } })
print article
# None
article = db.article.find_one({ 'authors.$id': { '$in': [ bob_id ] } })
print article
# None
article = db.article.find_one({ 'authors.$id': { '$in': [ str(bob_id) ] } })
print article
# { article object }
It results in that the string representation should be passed instead of the ObjectId
if I want to find any documents by DBRef
, in pymongo.
Does mongo or pymongo do just a string matching for that (and thus losing efficiency)? Is there any more proper way to do reference queries?