gpt4 book ai didi

java - 使用 Java 更新数组 MongoDB 中的元素

转载 作者:可可西里 更新时间:2023-11-01 10:42:11 26 4
gpt4 key购买 nike

示例 JSON 文档

{
"_id" : "ab85cebc-8c7a-43bf-8efc-1151ccaa4f84",
"address" : {
"city" : "Bangalore",
"postcode" : "560080",
"countrycode":"in",
"street" : "SADASHIVNAGAR,SANKEY TANK RD"
},
"brand" : "Shell",
"prices" : [
{
"fuelType" : "DIESEL",
"price" : 52.7
},
{
"fuelType" : "PETROL",
"price" : 67.05
}
]
}
  • 我有大约 20 个文档 用于 brand:Shell,位于类加罗尔及其周边地区的不同位置。
  • 对于所有这些,我必须更新DieselPetrol 价格。

假设当前的DIESELPETROL 价格分别是57.971.4

如何使用 JAVA(使用 Eclipse IDE)

用这些最新价格更新所有文档

代码(完整)

public class UpdateGasstationFuelPrice {

public static void main(String[] args) {
MongoClient client = new MongoClient("localhost",27017);
MongoDatabase db = client.getDatabase( "notes" );

MongoCursor<Document> cursor = db.getCollection( "gasstation" ).find( new BasicDBObject( "address.countrycode","in" )
.append("address.city","Bangalore")
.append("brand","Shell")).iterator();

if (cursor.hasNext()){
Document doc = cursor.next();
}
client.close();
}
}

使用查询更新

  db.getCollection("gasstation").update({"address.countrycode":"in","address.city":"Bangalore","brand":"Shell"},   
//Query to get the position
{
"prices": { $exists: true }
},
// Use the positional $ operator to update specific element (which matches your query
{
$set:
{
//set value specific to elements field/key
"prices" : [
{
"fuelType" : "DIESEL",
"price" : 502.7
},
{
"fuelType" : "PETROL",
"price" : 607.05
}
]
}
}
);

最佳答案

如果您知道要更新的元素的位置,则无法更新。

所以基本上你可以做的是:

  1. 您需要查询才能找到职位。
  2. 使用位置运算符并更新数组。
db.gasstation.update(    
//Query to get the position
{
"prices.fuelType": "DIESEL"
},
// Use the positional $ operator to update specific element (which matches your query
{
$set:
{
"prices.$" :
//Element/new value to update
{
"fuelType" : "DIESEL",
"price" : 999.7
}
}
}
);

如果您只想更新嵌入在数组中的 json 元素中的特定字段,您可以执行以下操作:

db.gasstation.update(    
//Query to get the position
{
"prices.fuelType": "DIESEL"
},
// Use the positional $ operator to update specific element (which matches your query
{
$set:
{
//set value specific to elements field/key
//i.e. Update documents in an Array
"prices.$.price" : 999.7
}
}
);


根据评论更新:

db.gasstation.update(    
//Query to match
{
"address.city":"Bangalore",
"brand":"Shell",
"countrycode":"in",
"prices": { $exists: true }
},
// Use $set operator & overwrite entire array
{
$set:
{
//Overwrite value
"prices" : [
{
"fuelType" : "DIESEL",
"price" : 502.7
},
{
"fuelType" : "PETROL",
"price" : 607.05
}
]
}
}
);

关于java - 使用 Java 更新数组 MongoDB 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37827382/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com