[英]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}
]
}
In avobe document how'll I delete the carpet which have lowest price using java driver? 在avobe文件中,如何使用Java驱动程序删除价格最低的地毯? ie, I've to delete
{ "type" : "carpet" , "price" : 704.48}
即,我必须删除
{ "type" : "carpet" , "price" : 704.48}
Try this: 尝试这个:
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();
}
My solution can be not very well )) but I wanted show you an alternate variant 我的解决方案可能不太好)),但我想向您展示一个替代的变体
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.