Pymongo find _id in subdocuments

Assuming this item is my database:

{"_id" : ObjectID("526fdde0ef501a7b0a51270e"),
  "info": "foo",
  "status": true,
  "subitems : [ {"subitem_id" : ObjectID("65sfdde0ef501a7b0a51e270"),
                 //more},
                {....}
              ],
  //more
}

I want to find (or find_one, it doesn't matter) a document with "subitems.subitem_id" : xxx.

I have tried the following. They all return an empty list.

from pymongo import MongoClient,errors
from bson.objectid import ObjectId

id = '65sfdde0ef501a7b0a51e270'

db.col.find({"subitems.subitem_id" : id } ) #obviously wrong
db.col.find({"subitems.subitem_id" : Objectid(id) })
db.col.find({"subitems.subitem_id" : {"$oid":id} })
db.col.find({"subitems.subitem_id.$oid" : id })
db.col.find({"subitems.$.subitem_id" : Objectid(id) })

In mongoshell, this works, however:

find({"subitems.subitem_id" : { "$oid" : "65sfdde0ef501a7b0a51e270" } })
+4
source share
2 answers

Double check. The correct answer. db.col.find({"subitems.subitem_id" : Objectid(id)}) Keep in mind that this query will return the full record, not just the corresponding part of the submatrix.

Mongolian shell:

a = ObjectId("5273e7d989800e7f4959526a")
db.m.insert({"subitems": [{"subitem_id":a},
                          {"subitem_id":ObjectId()}]})
db.m.insert({"subitems": [{"subitem_id":ObjectId()},
                          {"subitem_id":ObjectId()}]})
db.m.find({"subitems.subitem_id" : a })

>>> { "_id" : ObjectId("5273e8e189800e7f4959526d"), 
"subitems" : 
[
 {"subitem_id" : ObjectId("5273e7d989800e7f4959526a") },    
 {"subitem_id" : ObjectId("5273e8e189800e7f4959526c")} 
]}
+2
source

The literal is 65sfdde0ef501a7b0a51e270not hexadecimal, therefore, an invalid ObjectId.

, id Python. .

, , , . , .

.

from pymongo import MongoClient
from bson.objectid import ObjectId

db = MongoClient().database
oid = '65cfdde0ef501a7b0a51e270'

x = db.col.find({"subitems.subitem_id" : ObjectId(oid)})

print list(x)

, oid .

Mongo JavaScript.

db.col.find({"subitems.subitem_id" : new ObjectId("65cfdde0ef501a7b0a51e270")})
+3

All Articles