0

For some reason, I need to look up a collection with its entry ObjectId field. For example, how should I put up a query dictionary in the find() method, so that I get all entry with hex ObjectId matching '5c.*'.

> db.demoCommentCollection.find()
{
        "_id" : ObjectId("5c7fec06d2ea12b0cdc7a490"),
        "comment" : "Hi, I'm Al and I love Object Rocket and I love comments."
}
{
        "_id" : ObjectId("4db1ec06d2ea12b0cdc7a491"),
        "comment" : "This is Cameron. I enjoyed reading your Object Rocket tutorials."
}
{
        "_id" : ObjectId("5c7fec06d2ea12b0cdc7a492"),
        "userId" : 2,
        "comment" : "I'm Betty. This is my first comment on the site."
}
> db.demoCommentCollection.find({/* some query dict to query objectid hex start with '5c' */})
{
        "_id" : ObjectId("5c7fec06d2ea12b0cdc7a492"),
        "comment" : "I'm Betty. This is my first comment on the site."
}
{
        "_id" : ObjectId("5c7fec06d2ea12b0cdc7a490"),
        "comment" : "Hi, I'm Al and I love Object Rocket and I love comments."
}

1 Answer 1

1

Similar to How to find document by parts of ObjectId? you can use $where in pymongo.

db.mycollection.find({'$where': 'this._id.str.match(/^5c/)'})
Sign up to request clarification or add additional context in comments.

2 Comments

Does it have injection risk?
Certainly it is a higher risk, yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.