William.D
William.D

Reputation: 125

Why can't I find documents based on ObjectId?

So I have some documents with a format like this:

{
_id: ObjectId("5ca4bbc7a2dd94ee5816238c")
account_id: 371138
limit: 9000
products: Array
}

And I tried to query with this code in Python:

doc = col.find({"_id": ObjectId("5ca4bbc7a2dd94ee5816238c")})

But it always raises ValueError: ObjectId is not iterable. Was wondering if I'm missing something?

Upvotes: 1

Views: 809

Answers (2)

Belly Buster
Belly Buster

Reputation: 8814

Your find() syntax looks correct; so maybe it's something else; see if you can get the code snippet to work:

from pymongo import MongoClient
from bson.json_util import ObjectId

db = MongoClient()['mydatabase']
col = db.mycollection

col.insert_one({
    '_id': ObjectId("5ca4bbc7a2dd94ee5816238c"),
    'account_id': 371138,
    'limit': 9000,
    'products': 'Array'
})

doc = col.find({"_id": ObjectId("5ca4bbc7a2dd94ee5816238c")})
print(list(doc))

prints:

[{'_id': ObjectId('5ca4bbc7a2dd94ee5816238c'), 'account_id': 371138, 'limit': 9000, 'products': 'Array'}]

Upvotes: 1

Dead Guy
Dead Guy

Reputation: 57

use dictionary instead of this mess. Define it like that and read documentation on how to work with dictionaries. Code:-

details={
    "_id": ObjectId("5ca4bbc7a2dd94ee5816238c"),
    "account_id": 371138,
    "limit": 9000,
    "products": Array
}

Upvotes: 0

Related Questions