mongoDB查询“WHERE _id>阈" [英] mongoDB query "WHERE _id > threshold"

查看:338
本文介绍了mongoDB查询“WHERE _id>阈"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么能有一个类似于SQL的mongo查询... WHERE _id>阈值

我试过以下,但它不给我任何结果。

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

这是因为_id字段有点特别,它的格式是?

  _id:{$ oid:someid} 


解决方案

比较像like



_id mongo中的键不是(默认情况下)一个字符串 - 它是一个mongo objectId。

您需要比较相同类型才能获得有意义的结果:

  oid = new ObjectId(); 
db.things.find(_id:{$ gt:oid});



不读取mongoexport文件



Mongo导出文件如下所示:

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

这是一个对象id的json表示。 Mongo不希望在实际查询数据库时使用这种语法。这是行不通的:

 #将不起作用
db.things.find(_ id。$ oid: {$ gt:string});



id作为字符串



如果您有一个字符串的id,你会这样:

  str =123456789012345678901234; 
oid = new ObjectId(str);
db.things.find(_id:{$ gt:oid});



id作为部分字符串



如果你的字符串不是一个有效的oid(不是24个字符长),你只会从mongo得到一个异常,或者根据你的驱动程序得到一个新的oid。如果您有部分对象ID,则可以使用0填充以生成有效的oid,因此可以通过部分对象ID查找。例如:

  oid = new ObjectId(str +0000); 
db.things.find(_id:{$ gt:oid});


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"} 

解决方案

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:

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:

str = "123456789012345678901234";
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.:

oid = new ObjectId(str + "0000");
db.things.find(_id: {$gt: oid});

这篇关于mongoDB查询“WHERE _id>阈"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆