MongoDB 更新数组元素(带键的文档)如果存在,否则推送 [英] MongoDB Update array element (document with a key) if exists, else push

查看:22
本文介绍了MongoDB 更新数组元素(带键的文档)如果存在,否则推送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的架构:

doc:
{
    //Some fields
    visits:
    [
        {
            userID: Int32
            time: Int64
        }
    ]

}

我想先检查一个特定的userID是否存在,如果不存在,用那个userID和系统time推送一个文档,否则只是更新 time 值.我知道 $push$addToSet 都无法做到这一点.由于官方 documentation 建议,其中指出 DB 将在尝试更新插入时使用 $ 作为字段名称而不是运算符.

I want to first check if a specific userID exists, if not, push a document with that userID and system time, else just update time value. I know neither $push nor $addToSet are not able to do that. Also using $ with upsert:true doesn't work, because of official documentation advice which says DB will use $ as field name instead of operator when trying to upsert.

请指导我.谢谢

推荐答案

您可以使用 $addToSet 将项目添加到数组,并使用 $set 更新现有的此数组中的项目.

You can use $addToSet to add an item to the array and $set to update an existing item in this array.

如果在数组中找不到 userID,以下将向数组添加一个新项目:

The following will add a new item to the array if the userID is not found in the array :

db.doc.update({
    visits: {
        "$not": {
            "$elemMatch": {
                "userID": 4
            }
        }
    }
}, {
    $addToSet: {
        visits: {
            "userID": 4,
            "time": 1482607614
        }
    }
}, { multi: true });

如果匹配userId,以下将更新子文档数组项:

The following will update the subdocument array item if it matches the userId :

db.doc.update({ "visits.userID": 2 }, {
    $set: {
        "visits.$.time": 1482607614
    }
}, { multi: true });

这篇关于MongoDB 更新数组元素(带键的文档)如果存在,否则推送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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