mongodb:upserting:仅在插入文档时设置值 [英] mongodb: upserting: only set value if document is being inserted

查看:66
本文介绍了mongodb:upserting:仅在插入文档时设置值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个简单的mongo文档结构:

Considering a simple mongo document structure:

{_id,firstTime,lastTime}

{ _id, firstTime, lastTime }

客户需要插入具有已知ID的文档,或更新现有文档. "lastTime"应始终设置为某个最新时间.对于"firstTime",如果要插入文档,则"firstTime"应设置为当前时间.但是,如果已经创建了文档,则"firstTime"保持不变.我只想使用upserts(以避免查找).

The client needs to insert a document with a known ID, or update an existing document. The 'lastTime' should always be set to some latest time. For the 'firstTime', if a document is being inserted, then the 'firstTime' should be set to current time. However, if the document is already created, then 'firstTime' remain unchanged. I would like to do it purely with upserts (to avoid look ups).

我已经抓取了 http://www.mongodb.org/display/DOCS/Updating ,但我看不出该特定操作如何完成.

I've crawled the http://www.mongodb.org/display/DOCS/Updating, but I just don't see how that particular operation can be done.

我不认为这是不合理的,有$ push和$ addToSet操作可以有效地对数组字段执行此操作,而没有任何操作可以对简单字段执行相同的操作.好像应该有$ setIf操作之类的东西.

I don't believe this is something unreasonable, there are $push and $addToSet operations that effectively do that on array fields, just nothing that would do the same on simple fields. It's like there should be something like $setIf operation.

推荐答案

我遇到了完全相同的问题,没有针对< 2.4的简单解决方案,但是自2.4版本以来, $ setOnInsert 运算符让您完全做到这一点.

I ran into the exact same problem and there was no simple solution for <2.4 however since 2.4 the $setOnInsert operator let's you do exactly that.

db.collection.update( <query>,
                      { $setOnInsert: { "firstTime": <TIMESTAMP> } },
                      { upsert: true }
                    )

有关更多信息,请参见 2.4发行说明信息.

See the 2.4 release notes of setOnInsert for more info.

这篇关于mongodb:upserting:仅在插入文档时设置值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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