简体   繁体   中英

How to represent the following query(mongodb) in java

I have a JSON in MongoDB with the following structure:

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

    }
}

To retrieve JSON with storageData equal to null , in MongoDB I query as:

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

It gives me list of JSON bodies with empty storageData . So how do I represent that in Java

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

I am getting an error near BasicDBObject("$gt",{}))...

How do I represent ("$gt",{}) in Java??

First understand that null is a valid value. 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.

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:

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

I would do it via query, and not in Java because it would alleviate cpu time and memory.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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