[英]mongodb conditional query greater than $gt returns zero results
I have a mongodb database which has a users collection containing the following document 我有一个mongodb数据库,其中包含一个包含以下文档的用户集合
{
"_id": ObjectId("5161446e03642eab4a818fcd"),
"id": "35",
"userInfo": {
"name": "xyz",
"rollNumber": 121
}
}
I want to get all the rows whose id is greater than a specific value 我想获取所有ID大于特定值的行
@GET
@Path("/query")
@Produces({ MediaType.APPLICATION_JSON })
public List<String> getLactionInfo(@QueryParam("from") int from) {
BasicDBObject query = new BasicDBObject();
// check if ids greater than 0
query.put("id", new BasicDBObject("$gt", from));
// get the collection of users
DBCursor cursor = getTable("users").find(query);
List<String> listUsers = new ArrayList<String>();
while (cursor.hasNext()) {
DBObject object = cursor.next();
String id = cursor.next().get("_id").toString();
object.put("_id", id);
String objectToString = object.toString();
listUsers.add(objectToString);
}
return listUsers;
}
When I debugged my code its showing that the listUsers is null.Also when I manually run the following query in the console I get no results. 当我调试代码时,它显示listUsers为null。此外,当我在控制台中手动运行以下查询时,我也没有结果。
db.users.find({id:{$gt:60}})
The id
in your sample data is stored as a string
. 样本数据中的id
以string
形式存储。 So, the $gt
check is trying to compare an integer
to a string
. 因此, $gt
检查试图将integer
与string
进行比较。
If you switch your id
value to an integer
, it should work as expected. 如果将id
值切换为integer
,则它将按预期工作。
For example: 例如:
db.test.insert( { "id": 40, "name": "wired" } )
db.test.insert( { "id": 60, "name": "prairie" } )
db.test.insert( { "id": 70, "name": "stack" } )
db.test.insert( { "id": 80, "name": "overflow" } )
db.test.insert( { "id": "90", "name": "missing" } )
Then, the test: 然后,测试:
> db.test.find({"id": { "$gt": 60 }}).pretty()
{
"_id" : ObjectId("516abfdf8e7f7f35107081cc"),
"id" : 70,
"name" : "stack"
}
{
"_id" : ObjectId("516abfe08e7f7f35107081cd"),
"id" : 80,
"name" : "overflow"
}
For a quick data fix up you could do something like this from the shell (paste as one line and change myCollection
to your collection name: 为了快速修复数据,您可以在shell中执行以下操作(将其粘贴为一行,并将myCollection
更改为您的集合名称:
db.myCollection.find().forEach(function(doc) { doc.id = parseInt(doc.id, 10);
db.test.save(doc); })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.