gpt4 book ai didi

mongodb - 有没有办法用单个查询更新列表?

转载 作者:IT老高 更新时间:2023-10-28 13:26:02 28 4
gpt4 key购买 nike

我知道以前有人问过这个问题,但情况不同。我想要一个这样的集合:

{
"_id" : ObjectId("4c28f62cbf8544c60506f11d"),
"pk": 1,
"forums": [{
"pk": 1,
"thread_count": 10,
"post_count": 20,
}, {
"pk": 2,
"thread_count": 5,
"post_count": 24,
}]
}

我想要做的是插入一个“论坛”项目,增加计数器或添加一个项目(如果它不存在)。

例如做这样的事情(我希望它有意义):

db.mycollection.update({
"pk": 3,
"forums.pk": 2
}, {
"$inc": {"forums.$.thread_count": 1},
"$inc": {"forums.$.post_count": 1},
}, true)

并且拥有:

{
"_id" : ObjectId("4c28f62cbf8544c60506f11d"),
"pk": 1,
"forums": [{
"pk": 1,
"thread_count": 10,
"post_count": 20,
}, {
"pk": 2,
"thread_count": 5,
"post_count": 24,
}]
},
{
"_id" : ObjectId("4c28f62cbf8544c60506f11e"),
"pk": 3,
"forums": [{
"pk": 2,
"thread_count": 1,
"post_count": 1,
}]
}

我肯定可以分三步完成:

  1. 用新项目更新整个集合
  2. addToSet 论坛项目到列表
  3. 使用位置运算符增加论坛项目计数器

也就是说:

db.mycollection.update({pk:3}, {pk:3}, true)
db.mycollection.update({pk:3}, {$addToSet: {forums: {pk:2}}})
db.mycollection.update({pk:3, 'forums.pk': 2}, {$inc: {'forums.$.thread_counter': 1, {'forums.$.post_counter': 1}})

您知道更有效的方法吗?TIA,德国

最佳答案

您可能已经发现,positional operator不能在 upserts 中使用:

The positional operator cannot be combined with an upsert since it requires a matching array element. If your update results in an insert then the "$" will literally be used as the field name.

因此,您将无法在单个查询中获得所需的结果。

必须将文档的创建与计数器更新分开。您自己的解决方案是在正确的轨道上。可以浓缩成以下两个查询:

// optionally create the document, including the array
db.mycollection.update({pk:3}, {$addToSet: {forums: {pk:2}}}, true)

// update the counters in the array item
db.mycollection.update({pk:3, 'forums.pk': 2}, {$inc: {'forums.$.thread_counter': 1, 'forums.$.post_counter': 1}})

关于mongodb - 有没有办法用单个查询更新列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3467480/

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