Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

java - How can I check whether a field exists or not in MongoDB?

I have created some documents and managed to make some simple queries but I can't create a query that would find documents where a field just exists.

For example suppose this is a document:

{  "profile_sidebar_border_color" : "D9B17E" , 
   "name" : "???? ???????" , "default_profile" : false , 
   "show_all_inline_media" : true , "otherInfo":["text":"sometext", "value":123]}

Now I want a query that will bring all the documents where the text in otherInfo has something in it.

If there is no text, then the otherInfo will just be like that: "otherInfo":[]

So I want to check the existence of the text field in otherInfo.

How can I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the $exists operator in combination with the . notation. The bare query in the mongo-shell should look like this:

db.yourcollection.find({ 'otherInfo.text' : { '$exists' : true }})

And a test case in Java could look like this:

    BasicDBObject dbo = new BasicDBObject();
    dbo.put("name", "first");
    collection.insert(dbo);

    dbo.put("_id", null);
    dbo.put("name", "second");
    dbo.put("otherInfo", new BasicDBObject("text", "sometext"));
    collection.insert(dbo);

    DBObject query = new BasicDBObject("otherInfo.text", new BasicDBObject("$exists", true));
    DBCursor result = collection.find(query);
    System.out.println(result.size());
    System.out.println(result.iterator().next());

Output:

1
{ "_id" : { "$oid" : "4f809e72764d280cf6ee6099"} , "name" : "second" , "otherInfo" : { "text" : "sometext"}}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...