使用 java 在 MongoDB 中仅检索对象数组中的查询元素

Retrieve only the queried element in an object array in MongoDB using java

假设我们在 MongoDB 集合中有以下文档:

{  
   "_id":ObjectId("562e7c594c12942f08fe4192"),
   "shapes":[  
      {  
         "shape":"square",
         "color":"blue"
      },
      {  
         "shape":"circle",
         "color":"red"
      }
   ]
},
{  
   "_id":ObjectId("562e7c594c12942f08fe4193"),
   "shapes":[  
      {  
         "shape":"square",
         "color":"black"
      },
      {  
         "shape":"circle",
         "color":"green"
      }
   ]
}

而 MongoDB 查询是

db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1});

谁能告诉我Java怎么写?

我正在使用:

List<BasicDBObject> obj = new ArrayList<>();
obj1.add(new BasicDBObject("shapes.color", "red"));
List<BasicDBObject> obj1 = new ArrayList<>();
obj2.add(new BasicDBObject("shapes.$", "1"));

BasicDBObject parameters1 = new BasicDBObject();
parameters1.put("$and", obj1);

DBCursor cursor = table.find(parameters1,obj2).limit(500);

我什么也没得到。

Mongo Shell find function 的语法是:

db.collection.find(query, projection)

query document Optional. Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document ({}).

projection document Optional. Specifies the fields to return in the documents that match the query filter.

当翻译它以供 Mongo Java 驱动程序执行时,您需要为 BasicDBObject 构建单独的实例;

  • 查询
  • 投影

这是一个例子:

MongoCollection<Document> table = ...;

// {"shapes.color": "red"}
BasicDBObject query = new BasicDBObject("shapes.color", "red");

// {_id: 0, 'shapes.$': 1}
BasicDBObject projection = new BasicDBObject("shapes.$", "1").append("_id", 0);

FindIterable<Document> documents = table
    // assign the query
    .find(query)
    // assign the projection
    .projection(projection);

System.out.println(documents.first().toJson());

鉴于您的问题中包含示例文档,上面的代码将打印出来:

{
  "shapes": [
    {
      "shape": "circle",
      "color": "red"
    }
  ]
}

这与 db.test.find({"shapes.color": "red"}, {_id: 0, 'shapes.$': 1}); 的输出相同。