gpt4 book ai didi

mongodb - $unwind 2个字段分别在mongodb查询中

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

我想要$unwind 2 个字段,schoolhome。数据库结构是这样的;

{ 
"id" : 1,
"school" : [
{
"path" : "school1",
"code" : "code1",
},
{
"path" : "school2",
"code" : "code2",
},
{
"path" : "school3",
"code" : "code3",
},
{
"path" : "school4",
"code" : "code4",
}
],
"home" : [
{
"path" : "home1",
"code" : "homeCode1",
},
{
"path" : "home2",
"code" : "homeCode2",
},
]
}

我想要 $unwind schoolhome 字段并将它们分别作为;

{ 
"id" : 1,
"school" : [
{
"path" : "school1",
"code" : "code1",
}
},
{
"id" : 1,
"school" : [
{
"path" : "school2",
"code" : "code2",
}
},
{
"id" : 1,
"school" : [
{
"path" : "school3",
"code" : "code3",
}
},
{
"id" : 1,
"school" : [
{
"path" : "school4",
"code" : "code4",
}
},
{
"id" : 1,
"home" : [
{
"path" : "home1",
"code" : "homeCode1",
}
},
{
"id" : 1,
"home" : [
{
"path" : "home2",
"code" : "homeCode2",
}
}

我写的旨在获取上述格式的查询是;

db.collection.aggregate([
{$unwind: "$school"},
{$unwind: "$home"}
]).pretty()

但是查询的结果是成对的;

{
"id" : 1,
"school" : {
"path" : "school1",
"code" : "code1"
},
"home" : {
"path" : "home1",
"code" : "homeCode1"
}
}
{
"id" : 1,
"school" : {
"path" : "school1",
"code" : "code1"
},
"home" : {
"path" : "home2",
"code" : "homeCode2"
}
}
{
"id" : 1,
"school" : {
"path" : "school2",
"code" : "code2"
},
"home" : {
"path" : "home1",
"code" : "homeCode1"
}
}
{
"id" : 1,
"school" : {
"path" : "school2",
"code" : "code2"
},
"home" : {
"path" : "home2",
"code" : "homeCode2"
}
}
{
"id" : 1,
"school" : {
"path" : "school3",
"code" : "code3"
},
"home" : {
"path" : "home1",
"code" : "homeCode1"
}
}
{
"id" : 1,
"school" : {
"path" : "school3",
"code" : "code3"
},
"home" : {
"path" : "home2",
"code" : "homeCode2"
}
}
{
"id" : 1,
"school" : {
"path" : "school4",
"code" : "code4"
},
"home" : {
"path" : "home1",
"code" : "homeCode1"
}
}
{
"id" : 1,
"school" : {
"path" : "school4",
"code" : "code4"
},
"home" : {
"path" : "home2",
"code" : "homeCode2"
}
}

我怎样才能分别 $unwind 2 个字段,而不是这个结果对格式?

最佳答案

这不是直接可能的。对于 MongoDB 3.4,有一个可能的解决方法。 $facet 可用于在同一文档的单个阶段中执行多组管道操作。它对您的案例很有用。

db.collection.aggregate({
'$facet': {
'school': [{
'$unwind': '$school'
}, {
'$project': {
_id: '1',
school: 1
}
}],
'home': [{
'$unwind': '$home'
}, {
'$project': {
_id: '1',
home: 1
}
}]
}
}, {
'$project': {
'schoolAndHome': {
'$setUnion': ['$school', '$home']
}
}
}, {
'$unwind': '$schoolAndHome'
}, {
'$replaceRoot': {
'newRoot': '$schoolAndHome'
}
})

关于mongodb - $unwind 2个字段分别在mongodb查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42153622/

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