Mongodb upsert仅更新选定的字段,但插入所有字段 [英] Mongodb upsert only update selected fields, but insert all

查看:513
本文介绍了Mongodb upsert仅更新选定的字段,但插入所有字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用MongoDB中的upsert更新文档中的单个字段(如果找到),或者插入包含很多字段的全新文档.问题在于,在我看来,MongoDB要么替换了每个字段,要么在其upsert操作中插入了字段的子集,即它不能插入超出其实际需要更新的字段的数量.

I am trying to use upsert in MongoDB to update a single field in a document if found OR insert a whole new document with lots of fields. The problem is that it appears to me that MongoDB either replaces every field or inserts a subset of fields in its upsert operation, i.e. it can not insert more fields than it actually wants to update.

我想做的是以下事情:

  • 我查询一个唯一值
  • 如果文档已存在,则仅将时间戳值(称为"lastseen")更新为新值
  • 如果文档不存在,我将在文档中添加一长串不同的键/值对,这些键/值对应在其整个生命周期内保持不变.

让我们举例说明:

根据我的理解,此示例将在找到名称"的情况下更新"lastseen"日期,但如果未找到"name",则只会插入"name" +"lastseen".

This example would from my understanding update the 'lastseen' date if 'name' is found, but if 'name' is not found it would only insert 'name' + 'lastseen'.

db.somecollection.update({name: "some name"},{ $set: {"lastseen": "2012-12-28"}}, {upsert:true})

如果我在第二个参数中添加了更多字段(键/值对),并删除了$ set,则每个字段将在更新时被替换,但会对插入产生预期的效果.是否有类似$ insert或类似内容的东西仅在插入时才执行操作?

If I added more fields (key/value pairs) to the second argument and drop the $set, then every field would be replaced on update, but would have the desired effect on insert. Is there anything like $insert or similar to perform operations only when inserting?

所以在我看来,我只能获得以下一项:

So it seems to me that I can only get one of the following:

  • 正确的更新行为,但是如果文档不存在,则会插入仅包含所需字段子集的文档
  • 正确的插入行为,但是如果文档已经存在,则会覆盖所有现有字段

我的理解正确吗?如果是这样,是否可以通过一次操作解决?

Are my understanding correct? If so, is this possible to solve with a single operation?

推荐答案

MongoDB 2.4具有 $setOnInsert

MongoDB 2.4 has $setOnInsert

db.somecollection.update(
    {name: "some name"},
    {
        $set: {
            "lastseen": "2012-12-28"
        },
        $setOnInsert: {
            "firstseen": <TIMESTAMP>  # set on insert, not on update
        }
    },
    {upsert:true}
)

这篇关于Mongodb upsert仅更新选定的字段,但插入所有字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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