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

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

问题描述

我有这样的模式:

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

}

我想首先检查是否存在特定的userID,如果不存在,则推送具有该userID和系统time的文档,否则只需更新time值.我知道$push$addToSet都无法做到这一点.由于正式的文档,也无法将$upsert:true一起使用建议,其中说DB在尝试进行upsert时将使用$作为字段名而不是运算符.

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天全站免登陆