Mongodb:一次同时上传多个文档(使用$ in这样的键) [英] Mongodb: upsert multiple documents at the same time (with key like $in)

查看:68
本文介绍了Mongodb:一次同时上传多个文档(使用$ in这样的键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现MongoDB中有一个有趣的行为:

I stumbled upon a funny behavior in MongoDB:

当我跑步时:

db.getCollection("words").update({word:{$ in:["nico11"]}},{$ inc:{nbHits:1}},{multi:1,upsert:1})

如果不存在,它将创建"nico11",并将nbHits增加1(如预期).

it will create "nico11" if it doesn't exist, and increase nbHits by 1 (as expected).

但是,当我跑步时:

db.getCollection("words").update({ word: { $in: ["nico10", "nico11", "nico12"] } }, { $inc: { nbHits: 1 } }, { multi: 1, upsert: 1 })

它将正确更新数据库中已存在的密钥,但不插入丢失的密钥.

it will correctly update the keys that are already in the DB, but not insert the missing ones.

这是预期的行为吗,有什么办法可以向mongoDB提供一个数组,以便它更新现有元素并创建需要创建的元素?

Is that the expected behavior, and is there any way I can provide an array to mongoDB, for it to update the existing elements, and create the ones that need to be created?

推荐答案

根据

此更新根据参数,然后应用来自范围.比较操作将不会包含在新文档中.

The update creates a base document from the equality clauses in the parameter, and then applies the update expressions from the parameter. Comparison operations from the will not be included in the new document.

而且,不,没有方法可以使用简单的upsert实现您要在此处进行的操作.其原因可能是无法定义预期的结果.在您的特定情况下,可能会这样争论:哦,很明显,我们应该在这里做些什么".但是,想象一个更复杂的查询,像这样:

And, no, there is no way to achieve what you are attempting to do here using a simple upsert. The reason for that is probably that the expected outcome would be impossible to define. In your specific case it might be possible to argue along the lines of: "oh well, it is kind of obvious what we should be doing here". But imagine a more complex query like this:

db.getCollection("words").update({
    a: { $in: ["b", "c" ] },
    x: { $in: [ "y", "z" ]}
},
{ $inc: { nbHits: 1 } },
{ multi: 1, upsert: 1 })

在这种情况下,MongoDB应该做什么?

What should MongoDB do in this case?

但是,有批量写入操作在MongoDB中,您需要定义三个单独的

There is, however, the concept of bulk write operations in MongoDB where you would need to define three separate updateOne operations and package them up in a single request to the server.

这篇关于Mongodb:一次同时上传多个文档(使用$ in这样的键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆