gpt4 book ai didi

java - 带有 Java 驱动程序的 MongoDB - 使用 $addToSet 和 updateOne 将新集添加到嵌套数组

转载 作者:行者123 更新时间:2023-12-01 09:25:10 31 4
gpt4 key购买 nike

我有一个集合,其中包含如下所示的条目。

{
"_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)))));

但它不喜欢使用点表示法来访问数组的子数组。我收到以下错误...

Exception in thread "main" com.mongodb.MongoWriteException: can't append to array using string field name [daily_stats]

这可以通过一次更新实现吗?

最佳答案

monthly_activity 是一个数组,因此您需要使用位置值/运算符引用元素。

要标识更新字段,您只能使用位置运算符 $ 一次,即使该字段嵌套在数组中 ( a current limitation )。这需要您知道层次结构中其他数组元素的位置。在这种情况下,您需要知道 monthly_activitydaily_stats 的位置。

如果您有 monthly_activity 元素的位置(比如 0),那么您的更新字段可以通过 monthly_activity.0.daily_stats.$.stats 来识别。

The positional $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ placeholder is a single value.

关于java - 带有 Java 驱动程序的 MongoDB - 使用 $addToSet 和 updateOne 将新集添加到嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39891979/

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