0

嘿,我正在尝试允许用户在数组中更新他们的电子邮件。如果他们点击编辑,我想更新他们的特定电子邮件。我有旧值和新值,我知道我可以做一个拉和推,但想看看我是否可以更有效地做到这一点,将值与 $elemMatch 匹配,然后 $set 与新值匹配?我尝试了位置运算符,但它不适用于数组中没有键关系含义字段x的值:值x ...这是我的尝试,不知道该怎么做?欢迎其他方向。

User.findByIdAndUpdate(req.signedCookies.userid,{
            emailList: { $elemMatch: {oldEmail, {$set: {req.body.updateEmail}}}}
        }, function(err, userX) {});
4

1 回答 1

0

MongoDB 语法将是

> db.test.insert({userId: '1234', emailList: ['abc', 'def']})
> db.test.find()
{ "_id" : ObjectId("520eaade49177daf439a2ffa"), userId: '1234', "emailList" : [ "abc", "def" ] }
> db.test.update({userId: '1234', emailList: 'abc'}, {$set: {'emailList.$': 'ghi'}})
> db.test.find()
{ "_id" : ObjectId("520eaade49177daf439a2ffa"), userId: '1234', "emailList" : [ "ghi", "def" ] }
>

然后猫鼬代码将是

User.findOneAndUpdate({userId: '1234', emailList: 'abc'}, {$set: {'emailList.$': 'ghi'}})

这将允许您在一个查询中进行更改,而不是 $pull 和 $push

由于您搜索的是值数组而不是文档数组,因此不需要 $elemMatch。您可以直接查询数组,MongoDB 知道在其中查看并匹配一个值。

于 2013-08-16T22:44:03.480 回答