mongoDB query "WHERE _id > threshold"
Asked Answered
M

2

32

How can I have a mongo query similar to the SQL "...WHERE _id > threshold"

I tried the following, but it doesn't give me any result.

 db.things.find(_id: {$gt: someid} });

Is it because the _id field is a little special, in that it has the format?

_id : {"$oid" : "someid"} 
Millstream answered 15/6, 2012 at 14:9 Comment(0)
R
46

Compare like with like

The _id key in mongo is not (by default) a string - it is a mongo objectId.

You need to compare to the same type to get a meaningful result:

var ObjectId = require('mongodb').ObjectID;
var oid = new ObjectId();
db.things.find(_id: {$gt: oid});

Don't read mongoexport files

Mongo export files look like this:

{ "_id" : { "$oid" : "4f876b00c56da1fa6a000030" }, ...

This is a json representation of an object id. Mongo doesn't want you to use that kind of syntax when actually querying the db. This will not work:

# will not work
db.things.find("_id.$oid": {$gt: "string"});

id as a string

If you have the id as a string, you'd do:

var ObjectId = require('mongodb').ObjectID;
var str = "123456789012345678901234";
var oid = new ObjectId(str);
db.things.find(_id: {$gt: oid});

id as a partial string

If the string you have is not a valid oid (not 24 chars long), you'll just get an exception from mongo - or depending on your driver, a new oid. If you have a partial object id you can pad with 0s to make a valid oid and therefore permit finding by partial object ids. e.g.:

var ObjectId = require('mongodb').ObjectID;
var oid = new ObjectId(str + "0000");
db.things.find(_id: {$gt: oid});
Roana answered 15/6, 2012 at 14:15 Comment(4)
usefull: var ObjectId = require('mongodb').ObjectIDDint
One Liner : db.things.remove({_id:{$gt:ObjectId("5981584647e32e386a96d61e")}}) , may help someone.Spiral
Is this in the mongodb docs?Maseru
@JosielFaleiros I wouldn’t expect so - it’s not common to want to do what was asked here. However it’s possible things changed since I looked 10 years ago :) I’d start here.Roana
A
0

For those who are looking for mongo shell command:

db.getCollection('things').find({_id: {$gt: ObjectId("65d61b7ecec1a17b2da11a77")}})
Augustaaugustan answered 28/2 at 13:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.