20

いくつかのドキュメントを作成し、いくつかの簡単なクエリを作成できましたが、フィールドが存在するだけのドキュメントを検索するクエリを作成できません。

たとえば、これがドキュメントであるとします。

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

ここで、テキストが含まれているすべてのドキュメントを取得するクエリが必要ですotherInfo

テキストがない場合は、次のotherInfoようになります。"otherInfo":[]

textそこで、のフィールドの存在を確認したいと思いotherInfoます。

どうすればこれを達成できますか?

4

4 に答える 4

58

演算子は表記$existsと組み合わせて使用​​できます。.mongo-shellのベアクエリは次のようになります。

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

また、Javaのテストケースは次のようになります。

    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());

出力:

1
{ "_id" : { "$oid" : "4f809e72764d280cf6ee6099"} , "name" : "second" , "otherInfo" : { "text" : "sometext"}}
于 2012-04-07T20:10:47.967 に答える
2

または、次を使用できます。

import static com.mongodb.client.model.Filters.exists;

Document doc = (Document) mongoCollection.find(exists("otherInfo")).first();
于 2018-05-06T19:15:11.420 に答える
1

このcom.mongodb.QueryBuilderクラスを使用して、Mattの回答で提供されているクエリを作成できます。

QueryBuilder queryBuilder = QueryBuilder.start("otherInfo.text").exists(true);
DBObject query = queryBuilder.get();
DBCursor dbCursor = collection.find(query);
于 2018-05-29T06:06:23.603 に答える
0

inクエリは、以下を参照してください。テキスト値を持つすべての要素を除外しません。

db.things.find({otherInfo:{$in: [text]}});

BasicDBObject query = new BasicDBObject();
query.put("otherInfo", new BasicDBObject("$in", "[text]"));
var result = db.find(query);
于 2012-04-07T19:59:57.493 に答える