MongoDb:在文档中使用条件将元素的属性投影到数组中



我有以下一系列书籍。我正在尝试在数组中投影元素的单个属性。

我的查询正在注释数组中投影文本属性,以book year 2012 author A1

示例书籍数组:

[
    {
        book_id: "1",
        title:'B1',
        year: 2012,
        comments: [
            {
                author: "A1",
                text: "C1"
            }
        ]
    },
    {
        book_id: "2",
        title:'B2',
        year: 2012,
        comments: [
            {
                author: "A2",
                text: "C2.0"
            },
            {
                author: "A1",
                text: "C2.1"
            },
            {
                author: "A1",
                text: "C2.2"
            },
        ]
    },
    {
        book_id: "3",
        title:'B3',
        year: 2013,
        comments: [
            {
                author: "A1",
                text: "C3"
            }
        ]
    },
]

预期成果


[
    "C1",
    "C2.1",
    "C2.2"
]

我尝试了以下方法:


// query using find
db.books.find(
{year:2012, comments: {$elemMatch : {author:"A1" } } },{_id:0,'comments.text':1}
)
// results
/* 1 */
{
    "comments" : [ 
        {
            "text" : "C1"
        }
    ]
}
/* 2 */
{
    "comments" : [ 
        {
            "text" : "C2.0"
        }, 
        {
            "text" : "C2.1"
        }, 
        {
            "text" : "C2.2"
        }
    ]
}

// query using aggregation

db.books.aggregate(
[
    {$match: {year:2012}},
    {
        $project:{
            comments: {
                $filter:{
                    input: "$comments",
                    as:'comment',
                    cond: {$eq:['$$comment.author','A1']}
                }
            }
        }
     }
])
// results in
/* 1 */
{
    "_id" : ObjectId("5d3446f9d9eac0ed968aad4b"),
    "comments" : [ 
        {
            "author" : "A1",
            "text" : "C1"
        }
    ]
}
/* 2 */
{
    "_id" : ObjectId("5d3446f9d9eac0ed968aad4c"),
    "comments" : [ 
        {
            "author" : "A1",
            "text" : "C2.1"
        }, 
        {
            "author" : "A1",
            "text" : "C2.2"
        }
    ]
}

您可以使用

以下聚合

db.collection.aggregate([
  { "$match": { "year": 2012, "comments": { "$elemMatch": { "author": "A1" }}}},
  { "$unwind": "$comments" },
  { "$match": { "year": 2012, "comments.author": "A1" }},
  { "$group": {
    "_id": null,
    "data": { "$push": "$comments.text" }
  }}
])

输出

[
  {
    "_id": null,
    "data": [
      "C1",
      "C2.1",
      "C2.2"
    ]
  }
]

你不能用mongodb返回简单的数组字符串,因为它只返回BSON文档,而不仅仅是元素数组。

最新更新