如果值存在,mongodb如何更新数组中的值,或者只添加新记录

时间:2018-06-07 03:13:02

标签: mongodb mongodb-query

我是使用mongodb的新手 在我们的项目中,有一个" Events"集合和每个文档可以简化为:

{
    _id:"uuid4",
    events:
    [
        {
            "name":"event1",  //event name
            "occurs":3        //the number of event1 occurs 
        },
        {
            "name":"event2",
            "occurs":3
        }
    ]
}

我的期望:

  • 如果事件数组中存在事件名称,则incr发生1
  • 如果事件名称不在事件数组中,则添加新记录,名称为 事件名称,初始化为1
  • 只使用一个" sql"

如何做到这一点?

psudo代码应该是

def event_happens(id, eventname):
    # if id is uuid4, eventname is event1
    # result should be:
    # 
    # {
    #    _id:"uuid4",
    #    events:
    #    [
    #        {
    #            "name":"event1",  
    #            "occurs":4        //!!number incr to 4
    #        },
    #        {
    #            "name":"event2",
    #            "occurs":3
    #        }
    #    ]
    #}
    # if id is uuid4, eventname is event7
    # result should be:
    # 
    # {
    #    _id:"uuid4",
    #    events:
    #    [
    #        {
    #            "name":"event1",  
    #            "occurs":4        
    #        },
    #        {
    #            "name":"event2",
    #            "occurs":3
    #        },
    #        {
    #            "name":"event7", // add new record
    #            "occurs":1
    #        }
    #    ]
    #}

    collection.update({"id":id},{"some magic update query here..."})

0 个答案:

没有答案