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"}
_id field is reserved for primary key in mongodb, and that should be a unique value. If you don't set anything to _id it will automatically fill it with "MongoDB Id Object". But you can put any unique info into that field.
The default unique identifier generated as the primary key ( _id ) for a MongoDB document is an ObjectId. This is a 12 byte binary value which is often represented as a 24 character hex string, and one of the standard field types supported by the MongoDB BSON specification.
In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. This also applies to documents inserted through update operations with upsert: true.
According to MongoDB's manual the answer is yes, it's unique by default: MongoDB creates the _id index, which is an ascending unique index on the _id field, for all collections when the collection is created. You cannot remove the index on the _id field.
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});
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"});
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});
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});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With