gpt4 book ai didi

mongoDB:过滤数组数组

转载 作者:行者123 更新时间:2023-12-04 08:57:57 24 4
gpt4 key购买 nike

我有以下文件:

{

"name": "object1",
"subarray": [
{
"name": "subobject1",
"list": [
{
"date": "2020-01-01",
"name": "list1"
}
]
}
]
}
我正在尝试以下代码:
db.getCollection("table").aggregate([
{ "$match": { "name": "object1" } },
{ "$group": {
"_id": "$name",
"list_array": {
"$first": "$subarray.list"
}
}
}])
结果是以下文件:
{
"_id": "object1",
"list_array": [
[
{
"date": "2020-01-01",
"name": "list1"
}
]
]
}
我得到了一个数组数组,但我想要类似的东西
{
"_id": "object1",
"list_array": [
{
"date":"2020-01-01",
"name":"list1"
}
]
}
我的 $match 将始终只返回一个对象。我该怎么做?

最佳答案

随着您的阶段,只需添加

{
"$project": {
list_array: {
"$reduce": {
"input": "$list_array",
"initialValue": [],
"in": {
"$setUnion": [
"$$this",
"$$value"
]
}
}
}
}
}
工作 Mongo playground
如果您 unwind之前 group阶段,它也将提供预期结果 Answer with unwind

关于mongoDB:过滤数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63711135/

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