gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:01:36 26 4
gpt4 key购买 nike

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

我的查询正在为 author A1year 2012book 投影文本属性。

书籍数组示例:

[
{
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" }
}}
])

Output

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

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

关于MongoDb:在有条件的文档中将元素的属性投影到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57132422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com