简体   繁体   English

如何在Java中表示以下查询(MongoDB)

[英]How to represent the following query(mongodb) in java

I have a JSON in MongoDB with the following structure: 我在MongoDB中具有以下结构的JSON:

{
    id:"_234234",
    "stationId":"ALM",
    "storageData": {

    }
}

To retrieve JSON with storageData equal to null , in MongoDB I query as: 要在MongoDB中检索storageData等于null JSON, storageData查询为:

db.collection.find({"storageData":{"$gt" : {}}})

It gives me list of JSON bodies with empty storageData . 它为我提供了带有空storageData的JSON主体列表。 So how do I represent that in Java 那我怎么用Java表示

BasicDBObject obj=new BasicDDBObject("storageData", new BasicDBObject("$gt",{}));
collection.find(obj);

I am getting an error near BasicDBObject("$gt",{}))... 我在BasicDBObject("$gt",{}))...附近BasicDBObject("$gt",{}))...错误BasicDBObject("$gt",{}))...

How do I represent ("$gt",{}) in Java?? 如何用Java表示("$gt",{})

First understand that null is a valid value. 首先了解null是有效值。 This would be valid: 这将是有效的:

{
    id:"_234234",
    StationId:"ALM",
    StorageData: null 
}

and retrieving the document, asking for storagedata which is null would retrieve the doc with the id _234234. 并检索文档,要求存储数据为空将检索ID为_234234的文档。

If what you need is to check which documents DON'T have the key "storagedata" then use the $exist keyword or construct the query in this way: 如果您需要检查哪些文档没有关键字“ storagedata”,请使用$ exist关键字或以这种方式构造查询:

db.yourcollection.find("this.storagedata == null")

I would do it via query, and not in Java because it would alleviate cpu time and memory. 我会通过查询而不是在Java中完成此操作,因为这会减少CPU时间和内存。

All you want to to here is represent an empty object: 您只想代表一个空对象:

BasicDBObject query = new BasicDBObject(
    "storageData", new BasicDBObject(
        "$gt",new BasicDBObject()
     )
);

Which of course produces the query: 当然哪个产生查询:

{ "storageData" : { "$gt" : { } } }

So that's it, just call BasicDBObject without any arguments. 就是这样,只需不带任何参数的方式调用BasicDBObject

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM