![](/img/trans.png)
[英]How to update an object in a array using MongoDB Java Driver?
[英]How to access object nested inside an array in MongoDB using Java driver
{ "_id" : 0 ,
"prices" : [
{ "type" : "house" , "price" : 10345} ,
{ "type" : "bed" , "price" : 456.94} ,
{ "type" : "carpet" , "price" : 900.45} ,
{ "type" : "carpet" , "price" : 704.48}
]
}
在avobe文件中,如何使用Java驅動程序刪除價格最低的地毯? 即,我必須刪除{ "type" : "carpet" , "price" : 704.48}
嘗試這個:
DBCursor cursor = collection.find(new BasicDBObject("prices.type", "carpet"),
new BasicDBObject("prices", 1));
try {
while (cursor.hasNext()){
DBObject doc = cursor.next();
ArrayList<BasicDBObject> prices= (ArrayList<BasicDBObject>) doc.get("prices");
double minPrice = -1;
for(BasicDBObject dbObject: prices){
if (!dbObject.get("type").equals("carpet"))
continue;
double price= (Double) dbObject.get("price");
if (minPrice == -1) {
minPrice = price;
continue;
}
if (price< minPrice )
minPrice = price;
}
for (BasicDBObject dbObject: prices){
if (dbObject.get("type").equals("carpet") && (((Double) dbObject.get("price")) == minPrice)){
collection.update(new BasicDBObject("_id", doc.get("_id")),
new BasicDBObject("$pullAll", new BasicDBObject("prices", Arrays.asList(dbObject))));
System.out.println(dbObject);
}
}
}
} finally {
cursor.close();
}
我的解決方案可能不太好)),但我想向您展示一個替代的變體
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.