作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我知道以前有人问过这个问题,但情况不同。我想要一个这样的集合:
{
"_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,
}]
}
我肯定可以分三步完成:
也就是说:
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/
我是一名优秀的程序员,十分优秀!