[英]MongoDB with Java driver - Adding a new set to a nested array using $addToSet and updateOne
我有一個條目,如下所示。
{
"_id" : ObjectId("57f6021caa3e1d3ee099af0d"),
"user" : "JBL123",
"name" : "Joe Bloggs",
"monthly_activity" : [
{
"month" : "September2016",
"status" : "active",
"daily_stats" : [
{
"date" : "27/SEP/2016",
"stats" : [
{
"category":
"stat1":
"stat2":
},
{
"category":
"stat1":
"stat2":
}
]
},
{
"date" : "28/SEP/2016",
"stats" : [
{
"category": ...
"stat1": ...
"stat2": ...
},
{
"category": ...
"stat1": ...
"stat2": ...
}
]
},
],
"extra_fields": ....
}
]
}
我想在指定日期插入新類別的統計信息。
我嘗試了以下
mdb.getCollection("users").updateOne(new Document("user", "JBL123").append("monthly_activity.daily_stats.date", "27/SEP/2016"),
new Document("$addToSet", (new Document("monthly_activity.daily_stats.$.stats",
new Document("category",cat)
.append("stat1", s1)
.append("stat2", s2)))));
但是,它不喜歡使用點符號來訪問數組的子數組。 我收到以下錯誤...
線程“ main” com.mongodb.MongoWriteException中的異常:無法使用字符串字段名稱[daily_stats]追加到數組
是否可以通過單個更新?
monthly_activity
是一個數組,因此您需要使用位置值/運算符引用一個元素。
為了標識更新字段,即使字段嵌套在數組中( 當前限制 ),您也只能使用一次位置運算符$
。 這將需要您知道其他數組元素在層次結構中的位置。 在這種情況下,你將需要了解的任何位置monthly_activity
或daily_stats
。
如果您具有monthly_activity
元素的位置(例如0),那么您可以通過monthly_activity.0.daily_stats.$.stats
來標識更新字段。
位置$運算符不能用於遍歷一個以上數組的查詢,例如遍歷嵌套在其他數組中的數組的查詢,因為$占位符的替換是單個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.