[英]MongoDB - get all the elements from an array
I want to $match multiple items in $facet
operator from an dataset and return output in simple array form just like as it is before.我想从数据集中匹配$facet
运算符中的多个项目,并像以前一样以简单的数组形式返回 output。
Exception : I don't want to use array-names after $facet-stage
anywhere in my aggeration.例外:我不想在我的聚合中的任何地方在$facet-stage
之后使用数组名称。 because it becomes so difficult to handle those in my code.因为在我的代码中处理这些变得非常困难。 I think I can go with k
and v
or something.我想我可以用k
和v
之类的东西来 go。
I hope you understand我希望你明白
PlayGround Link : https://mongoplayground.net/p/Vw-GkPPHOiw游乐场链接: https://mongoplayground.net/p/Vw-GkPPHOiw
Dataset:数据集:
[
{
"_id": 2,
"title": "Melancholy III",
"artist": "Munch",
"tags": [
"woodcut",
"Expressionism"
]
},
{
"_id": 4,
"title": "The Great Wave off Kanagawa",
"artist": "Hokusai",
"tags": [
"woodblock",
]
},
{
"_id": 5,
"title": "The Persistence of Memory",
"artist": "Dali",
"tags": [
"painting",
"oil"
]
},
{
"_id": 7,
"title": "The Scream",
"artist": "Munch",
"tags": [
"Expressionism",
"painting",
"oil"
]
},
]
Query:询问:
db.collection.aggregate([
{
$facet: {
"field1": [
{
$match: {
"artist": "Munch"
}
}
],
"field2": [
{
$match: {
"artist": "Grosz"
}
}
]
}
},
// Below is query which I've tried to make it one array. But I want make it
// without using the name "field1" and "field2" anywhere from below after this stage.
// Is that possible to do??
{
$project: {
items: {
$concatArrays: [
"$field1",
"$field2"
]
}
}
}
])
Exprected Output:预计 Output:
[
{
"_id": 2,
"title": "Melancholy III",
"artist": "Munch",
"tags": [
"woodcut",
"Expressionism"
],
},
{
"_id": 7,
"title": "The Scream",
"artist": "Munch",
"tags": [
"painting",
"oil"
],
},
{
"_id": 1,
"title": "The Pillars of Society",
"artist": "Grosz",
"tags": [
"painting",
"Expressionism",
],
}
]
PlayGround : https://mongoplayground.net/p/Vw-GkPPHOiw游乐场: https ://mongoplayground.net/p/Vw-GkPPHOiw
You can additionally use unwind
and replaceRoot
to get the resulted object at root level您还可以使用unwind
和replaceRoot
在根级别获得结果 object
[
{
$facet: {
"field1": [
{ $match: { "artist": "Munch" } }
],
"field2": [
{ $match: { "artist": "Grosz" } }
]
}
},
{$project: {x: {$objectToArray: '$$ROOT'}}},
{$unwind: '$x'},
{$unwind: '$x.v'},
{$replaceRoot: {newRoot: '$x.v'}}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.