search by ObjectId in mongodb with pymongo
I use pymongo 2.4.1.
from bson.objectid import ObjectId
[i for i in dbm.neo_nodes.find({"_id": ObjectId(obj_id_to_find)})]
How do I search for an object by its ObjectId in the mongo console?
Not strange at all, people do this all the time. Make sure the collection name is correct (case matters) and that the ObjectId is exact.
Documentation is here
> db.test.insert({x: 1})
> db.test.find() // no criteria
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }
> db.test.find({"_id" : ObjectId("4ecc05e55dd98a436ddcc47c")}) // explicit
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }
> db.test.find(ObjectId("4ecc05e55dd98a436ddcc47c")) // shortcut
{ "_id" : ObjectId("4ecc05e55dd98a436ddcc47c"), "x" : 1 }
Pymongo find by _id in subdocuments
Double checked. Right answer is db.col.find({"subitems.subitem_id" : Objectid(id)})
Be aware that this query will return full record, not just matching part of sub-array.
Mongo 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")}
]}
What is the correct way to query MongoDB for _id using string by using Python?
It should be :
from pymongo.objectid import ObjectId
thing = db.things.find_one({'_id': ObjectId('4ea113d6b684853c8e000001') })
EDIT:
The current import is:from bson.objectid import ObjectId
Related Topics
Interact with Other Programs Using Python
Timedelta to String Type in Pandas Dataframe
Get Files Names Inside a Zip File on Ftp Server Without Downloading Whole Archive
Cx_Freeze Crashing Python 3.7.0
How to Format Axis Number Format to Thousands with a Comma in Matplotlib
Better Way to Shuffle Two Numpy Arrays in Unison
Insert an Item into Sorted List in Python
Import Win32API Error in Python 2.6
Differencebetween Join and Merge in Pandas
Recursively Iterate Through All Subdirectories Using Pathlib
How to Pip or Easy_Install Tkinter on Windows
How to Make the Width of the Title Box Span the Entire Plot
How to Check If an Object Is a List or Tuple (But Not String)
Get Number of Items from List (Or Other Iterable) with Certain Condition