[英]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)
查詢文檔可選。 使用查詢運算符指定選擇過濾器。 要返回集合中的所有文檔,請省略此參數或傳遞一個空文檔 ({})。
投影文件可選。 指定要在與查詢過濾器匹配的文檔中返回的字段。
將此翻譯為由 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});
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.