BSmith
BSmith

Reputation: 33

MongoDB query _id

So in my MongoDB test the _id field is a unique string in format of "SensorSN:YrMonthDay"

What I want to query is all data for 2016 month 3. But I can't quite get the Regex right.

So here is some sample _ids: 12345678:2016325 87654321:2016325

Basically I want to return both of the documents because they are in the month of March.

My first attempts have been similar to db.collection.find({'_id':'/:20163/'}) and so far no luck.

Thanks!

Upvotes: 0

Views: 306

Answers (2)

VtoCorleone
VtoCorleone

Reputation: 17203

Remove the quotes

db.collection.find({ _id: /:20163/ });

Or try using regex -

db.collection.find({ _id: { $regex: /:20163/ } });

https://docs.mongodb.com/manual/reference/operator/query/regex/

Upvotes: 1

dyouberg
dyouberg

Reputation: 2332

Take off the quotes, the find is looking for a string matching exactly that instead of doing the regex search.

db.collection.find({ '_id': /:20163/ })

or

db.collection.find({ _id: /:20163/ })

both work fine for me!

Your case would only match if your sample document was:

{ _id: "/:20163/" }

Upvotes: 2

Related Questions