MongoDB:使用不同的值更新和插入 [英] MongoDB: upsert with different values for update and insert

查看:483
本文介绍了MongoDB:使用不同的值更新和插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个小的上下文:我有一个文档为每个用户包含一个与用户相关的最近20个事件的数组。由于MongoDB没有这个功能(在文档中覆盖数组),我将推送我的事件并弹出最新的。

A little context: I have a document for each user that contains an array with latest 20 events related to a user. As MongoDB does not have this feature(to cap arrays inside a document), I will push my event and pop the latest one.

我的问题:初始化文档(也称为填充数组为null)。我想以原子方式:

My problem: initializing the document(aka filling array with nulls). I want to atomically:


  • 如果文档不存在,则创建包含具有20个空值的数组并推送一个值的文档


  • 更新文档),如果文档存在

您有其他建议吗?一个黑客我想到的是声明一个索引与:unique和:dropDups,并始终进行初始化插入。

Do you have any other suggestions? A hack I thought about would be to declare a index with :unique and :dropDups, and to always make an initialization insert.

相关: MongoDB固定大小数组实现

推荐答案

但是在单个操作中不可能。您希望 http://jira.mongodb.org/browse/SERVER-991 或< a href =http://jira.mongodb.org/browse/SERVER-453 =nofollow> http://jira.mongodb.org/browse/SERVER-453 。

Not possible in a single operation, yet. You want http://jira.mongodb.org/browse/SERVER-991 or http://jira.mongodb.org/browse/SERVER-453.

这篇关于MongoDB:使用不同的值更新和插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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