MongoDB如何获取子文档数组

时间:2017-09-07 06:34:50

标签: node.js mongodb nosql

我是使用Mongo的新手,我有一个看起来像这样的集合

{ 
    "_id" : "5e7a39ed-941a-4e07-af0b-df8764820206", 
    "title" : "Test Title Task", 
    "taskBody" : "This is a test task body", 
    "comments" : [
        {
            "_id" : "57b51a73-f585-4e80-ad51-107da707efd6", 
            "poster" : "Jack Black", 
            "comment" : "This is a comment"
        }, 
        {
            "_id" : "4ea314f3-3671-4568-b938-d8a1477ac681", 
            "poster" : "Joe Blow", 
            "comment" : "Another comment"
        }, 
        {
            "_id" : "c5f1a0e6-2fb9-429e-9931-8634f42fc143", 
            "poster" : "Mike Hall", 
            "comment" : " And yet Another comment"
        }
    ]
}

我试图通过传递ID来获取其中一个注释元素:

getCommentById(id) {
        return tasks().then((taskCollection) => {
            return taskCollection.find({ "comments._id": id }).toArray().then((commentQuery) => {
                if (!commentQuery) throw "Comment not found";
                return commentQuery;
            });
        });
    }

但是,它似乎返回了评论集合中的所有内容,而不仅仅是我在id中传递的一条评论。我怎样才能让它返回我正在传递id的注释?

这是调试窗口显示的内容

Array(1) [Object]
Object {_id: "5e7a39ed-941a-4e07-af0b-df8764820206", title: "Test Title Task", taskBody: "This is a test task body", …}

Array(3) [Object, Object, Object, …]
0: Object {_id: "57b51a73-f585-4e80-ad51-107da707efd6", poster: "Jack Black", comment: "Comment text 2"}

1: Object {_id: "4ea314f3-3671-4568-b938-d8a1477ac681", poster: "Joe Blow", comment: "Another comment"}

2: Object {_id: "c5f1a0e6-2fb9-429e-9931-8634f42fc143", poster: "Joe Blow", comment: "Another comment"}

我期待得到的回报只是:

{
    "_id" : "57b51a73-f585-4e80-ad51-107da707efd6", 
    "poster" : "Jack Black", 
    "comment" : "This is a comment"
}

假设“57b51a73-f585-4e80-ad51-107da707efd6”是传入的ID。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

taskCollection.find({ "comments": {$elemMatch: { _id: 'your value here '}}})

这应该适合你。

答案 1 :(得分:0)

您正在查询子数组。但你的假设是错误的。在使用数组字段的特定子文档查询时,查找查询仍将返回实际文档的列表。您不仅在单个文档的数组字段上执行find on collection。

使用mongoDB可以做的是:您可以排除或包含选择查询的字段。因此,您不会从mongoDB中读取不必要的字段,而是可以提高性能。您可以详细了解此here

所以对你的问题;虽然您只想读取数组字段中的子文档,但您也必须使用$运算符。您可以找到更多信息here

您的查询应如下所示:

db.collection.find({ "_id": "some id", "comments._id": "some id"}, {"comments.$": 1, "_id": 0})

但请再次记住:此查询仍会返回实际文档的列表(或使用findOne的一个集合),而不是评论。返回的json将如下所示:

{
  "comments": [
    {
      "_id" : "57b51a73-f585-4e80-ad51-107da707efd6", 
      "poster" : "Jack Black", 
      "comment" : "This is a comment"
    }
  ]
}

注意:如果您真的只想在问题中添加结构评论。您可以使用aggregation并在返回之前播放json的结构。