MongoDB聚合-在一个数组中显示来自不同数组的值
我有这类数据MongoDB聚合-在一个数组中显示来自不同数组的值,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有这类数据 { "_id" : 6444, "name" : [ { "name" : "John", "sourcesID" : [ 1, 2 ] }, { "name" : "Jack", "sourcesID" : [ 3, 4 ] }
{
"_id" : 6444,
"name" : [
{
"name" : "John",
"sourcesID" : [
1,
2
]
},
{
"name" : "Jack",
"sourcesID" : [
3,
4
]
}
],
"address" : [
{
"city" : "Chicago",
"sourcesID" : [
3,
4
]
},
{
"city" : "Boston",
"sourcesID" : [
5,
6
]
}
]
}
我希望聚合数据,以便能够匹配某个sourcesID,并找到来自此源的所有信息类型
这就是我希望实现的目标
{"type" : "name", "sourceID" : 1}
{"type" : "name", "sourceID" : 2}
{"type" : "name", "sourceID" : 3}
{"type" : "name", "sourceID" : 4}
{"type" : "address", "sourceID" : 3}
{"type" : "address", "sourceID" : 4}
{"type" : "address", "sourceID" : 5}
{"type" : "address", "sourceID" : 6}
感谢您的帮助。假设始终存在
sourceID
字段,您可以运行转换,以便能够动态读取对象键,然后运行三次以获取每个sourceID
的单个文档:
db.collection.aggregate([
{
$project: {
data: {
$filter: {
input: { $objectToArray: "$$ROOT" },
cond: {
$ne: [ "$$this.k", "_id" ]
}
}
}
}
},
{ $unwind: "$data" },
{ $unwind: "$data.v" },
{ $unwind: "$data.v.sourcesID" },
{
$project: {
_id: 0,
type: "$data.k",
sourceID: "$data.v.sourcesID"
}
}
])
它总是
sourcesID
还是有时sources
有时sourcesID
或者完全不可预测?很好!在我的例子中这是一个错误。都应该是sourcesID。我现在就修。