使用mongo

时间:2019-10-18 10:18:58

标签: node.js mongodb express mongoose mongodb-query

{
    "_id" : ObjectId("5da7c114753c6202f4f4d3b2"),

    "image" : "hem sopheap-1571275028119.jpg",
    "body" : "my first post\r\nyes this my post",
    "date" : ISODate("2019-10-17T00:59:18.901Z"),
    "comments" : [ 
        {
            "user" : "5d999578aeb073247de4bd6e",
            "fullname" : "hem sopheap",
            "username" : "sopheap",
            "comment" : "My first comment",
            "_id" : ObjectId("5da7c125753c6202f4f4d3b4"),
            "replies" : []
        }, 
        {
            "user" : "5da85558886aee13e4e7f044",
            "fullname" : "soeng kanel",
            "username" : "",
            "comment" : "Mr. kansael comment",
            "_id" : ObjectId("5da8557f886aee13e4e7f045"),
            "replies" : [],
            "date" : ISODate("2019-10-17T10:10:37.394Z"),
            "likes" : [ 
             "5d999578aeb073247de4bd6e", 
             "5d999578aeb073247de4bd6f"
            ]
        }
    ],
    "__v" : 41,
    "likes" : [ 
            "5d999578aeb073247de4bd6e", 
            "5d999578aeb073247de4bd6p"
        ]
}

我想获取特定likes的所有comments,而不是post SQL语句中类似以下内容:

db.posts.find({
  "comments": {
    $elemMatch: {
      "_id": ObjectId("5da8557f886aee13e4e7f045")
    }
  }
}, {
  likes:"$comments", _id:0
}).pretty()

,预期结果应该是这样

"likes" : [ "5d999578aeb073247de4bd6e", "5d999578aeb073247de4bd6f" ]

1 个答案:

答案 0 :(得分:1)

  

了解有关$elemMatch

的信息

这是您的完整查询

db.posts.find({
  "comments": {
    $elemMatch: {
      "user": "5da85558886aee13e4e7f044",
      "_id": ObjectId("5da8557f886aee13e4e7f045")
    }
  }
}, {
  likes:"$comments.likes", _id:0
}).pretty()

说明:

人们在基于数组子文档的多个字段进行过滤时常犯的一个常见错误是简单地执行{"comments._id": "something", "comments.user": "something"}之类的操作,该操作会返回数组子文档中所有与id,user相匹配的项目。解决这个问题的方法是$elemMatch