1

How can I do this in the MongoDB shell?

https://stackoverflow.com/a/14315888/8887398

Basically I'm trying to find objects by their ObjectId. All are failing so I assume it's trying to compare to string. I'm doing this directly in the MongoDB shell. Here's what I've tried:

db.myTestDB.find( {_id: 3254ummx213u5k815mn2v2 })
Result: SyntaxError: identifier starts immediately after numeric literal

db.myTestDB.find( {_id: "3254ummx213u5k815mn2v2" })
Result: Nothing

db.myTestDB.find( { "_id": "3254ummx213u5k815mn2v2" })
Result: Nothing

db.myTestDB.find( {_id: ObjectId("3254ummx213u5k815mn2v2") })
Result: Nothing

I just put a random ID in there for my examples, but I've verified the ID exists, and by looking on MongoDB Compass.

Birdman
  • 1,404
  • 5
  • 22
  • 49

1 Answers1

0

From the docs, you construct an ObjectId by using the new keyword. For example:

db.myTestDB.find( {_id: new ObjectId("3254ummx213u5k815mn2v2") })

So, you were on the right track with the last attempt in your question, you were only missing the new keyword.

Here's a more complete example. Given the following docs:

db.getCollection('X').find({})

{
    "_id" : ObjectId("59d0ada3c26584cd8b79fc51"),
    "name" : "A"
}
{
    "_id" : ObjectId("59d0adafc26584cd8b79fc54"),
    "name" : "B"
}
{
    "_id" : ObjectId("59d0b2b4c26584cd8b79fd7c"),
    "name" : "C"
}

This shell command will load one of those docs, by id:

db.getCollection('X').find({_id: new ObjectId("59d0ada3c26584cd8b79fc51")})

{
    "_id" : ObjectId("59d0ada3c26584cd8b79fc51"),
    "name" : "A"
}
glytching
  • 44,936
  • 9
  • 114
  • 120