匹配数组中的两个元素

时间:2019-07-27 08:50:13

标签: mongodb express

我有这个猫鼬查询:

Posts.updateOne({  _id: fields.opin_id, "comments._id" : 
fields.comment_id, "comments.user_id" : fields.user_id}, {$set: 
{"comments.$.body" : fields.comment } },......

其中注释是数组的一部分。我想做的是通过comment_id和user_id匹配数组的一个元素,但是当我更新数组时,它总是第一个带有user_id的元素被更新。 comments._id被忽略。我已经尝试过

$and: [{"comments._id" : 
    fields.comment_id}, {"comments.user_id" : fields.user_id}]

我在做什么错?

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么在主模型上的注释字段本质上就是这样的对象数组:

comments = [
 {
 _id: 'firstComment',
 body: "AAA"
 },
 {
  _id: 'secondComment'
  body: 'BBB',
 }] 

如果是这种情况,您要使用的是$elemMatch。这是Mongo docs。您的查询将如下所示:

Posts.updateOne({  _id: fields.opin_id, 
comments: { $elemMatch: {_id : fields.comment_id, user_id : fields.user_id}}}, 
{$set:{...}})