假設我有一個需要在 Mongodb 中更新的 JSON 物件,例如
{
"_id": 12345,
"Attribute": { "Property1": "X", "Property2": true, "Property3": 123 }
}
假設我在 mongoDb 中有一個記錄
{
"_id": 12345,
"Attribute1": "abc",
"Attribute2": "xyz",
"Attribute": { "Property4": "X", "Property2": false, "Property3": 456 }
}
結果應更新屬性 JSON,同時僅更新已更改的欄位并保持其余值不變。db 中的結果記錄應該是這樣的
{
"_id": 12345,
"Attribute1": "abc",
"Attribute2": "xyz",
"Attribute": { "Property4": "X", "Property1": "X", "Property2": true, "Property3": 123 }
}
我真的不知道如何使用 JAVA spring boot 在 Mongodb 中的 single Pass 中實作這一點。任何人都可以幫忙嗎?任何幫助表示贊賞。
uj5u.com熱心網友回復:
您可以使用 org.springframework.data.mongodb.core.query 包中的 Update 類。您可以撰寫如下代碼片段。
Update updateAttribute = new Update();
updateAttribute.push("Attribute", "Your Value");
mongoOperations.updateFirst(new Query(Criteria.where("id").is(12345)), updateAttribute, "yourCollection");
此外,您需要從 org.springframework.data.mongodb.core 包中為 MongoOperations 注入建構式。
uj5u.com熱心網友回復:
你可以通過兩種方式做到這一點,
- 對于 Mongo 4.4 版本,您可以使用流水線更新,這允許在更新主體中使用聚合運算子,特別是我們要使用$mergeObjects,如下所示:
db.collection.update(
{
_id: 12345
},
[
{
$set: {
Attribute: {
$mergeObjects: [
"$Attribute",
{
"Property1": "X",
"Property2": true,
"Property3": 123
}
]
}
}
}
])
蒙戈游樂場
- 對于較小的 Mongo 版本,您必須在代碼中構建更新主體,這是一個 javascript 示例(在 spring 中可能會稍微煩人一些)
const input = {
'_id': 12345,
'Attribute': { 'Property1': 'X', 'Property2': true, 'Property3': 123 },
};
const updateBody = {};
Object.keys(input.Attribute).forEach((key) => {
const updateKey = `Attribute.${key}`;
updateBody[updateKey] = input.Attribute[key];
});
db.collection.updateOne({ _id: 12345 }, { $set: updateBody });
通過在更新正文中使用點表示法,我們確保不會覆寫Attribute.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/397764.html
