Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching by ID in MongoDB not working

I'm setting up some basic searches in MongoDB, and while I'm able to find records by "ObjectId," I can't search by "_id". I'm conducting searches both directly in the Mongo console and writing search code in Atom, which I'm then running in a nodemon server.

 db.collection.find( { ObjectId( _id: "abcdefg" ) } ) // Returns a result 
 db.collection.find( { _id: "abcdefg" } )             // Returns null

The problem: If I enter search (1) into the console, it returns a result, yet when I enter the same search into Atom and run through nodemon, nodemon throws an error because "ObjectId" is undefined. (2) Always returns null, regardless of where I enter the search.

Are there any workarounds for this issue? Thanks!

like image 923
Brennan Avatar asked Dec 30 '25 10:12

Brennan


1 Answers

Try

db.collection.find({"_id" : ObjectId("abcdefg")})

Side note. It is a better practice to have your keys in double quotes in json. Make that in to a habit.

like image 91
ODelibalta Avatar answered Jan 01 '26 23:01

ODelibalta