mongoDB 查询 "WHERE _id >阈值" [英] mongoDB query "WHERE _id > threshold"
问题描述
我怎样才能有一个类似于 SQL "...WHERE _id > threshold" 的 mongo 查询
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} });
是不是因为_id字段有点特殊,有格式?
Is it because the _id field is a little special, in that it has the format?
_id : {"$oid" : "someid"}
推荐答案
比较喜欢和喜欢
mongo 中的 _id
键(默认情况下)不是字符串 - 它是 mongo objectId.
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});
不要阅读 mongoexport 文件
Mongo 导出文件如下所示:
Don't read mongoexport files
Mongo export files look like this:
{ "_id" : { "$oid" : "4f876b00c56da1fa6a000030" }, ...
这是一个对象 id 的 json 表示.Mongo 不希望您在实际查询数据库时使用这种语法.这将不起作用:
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 作为字符串
如果你有一个字符串形式的 id,你会这样做:
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 作为部分字符串
如果您拥有的字符串不是有效的 oid(长度不是 24 个字符),您只会从 mongo 中得到一个异常 - 或者根据您的驱动程序,一个新的 oid.如果您有部分对象 id,您可以用 0 填充以生成有效的 oid,因此允许通过部分对象 id 进行查找.例如:
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});
这篇关于mongoDB 查询 "WHERE _id >阈值"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!