MongoDB更新数组元素(带有键的文档)(如果存在),否则推送 [英] MongoDB Update array element (document with a key) if exists, else push
问题描述
我有这样的模式:
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屋!