假设我有一个mongodb文档
{
"id" : 1,
"types" : ["online" ,"offline"],
"applications" : [ ["online", "online"], ["offline"] ]
}我想变身为
{
"id" : 1,
"types" : [
{
"type" : "online",
"count" : 2,
"applications" : [ "online", "online"]
},
{
"type" : "offline",
"count" : 1,
"applications" : [ "offline" ]
}
]
}在这里,类型和应用程序数组可以是任何大小。
发布于 2019-10-04 10:00:45
您可以通过两个步骤完成此操作,首先使用$map和$filter将type与applications匹配,然后运行$reduce以获取count
db.collection.aggregate([
{
$project: {
id: 1,
types: {
$map: {
input: "$types",
as: "type",
in: {
type: "$$type",
applications: {
$filter: {
input: "$applications",
as: "application",
cond: {
$allElementsTrue: {
$map: { input: "$$application", in: { $eq: [ "$$this", "$$type" ] } }
}
}
}
}
}
}
}
}
},
{
$addFields: {
types: {
$map: {
input: "$types",
in: {
$mergeObjects: [
"$$this",
{
count: {
$reduce: {
input: "$$this.applications",
initialValue: 0,
in: { $add: [ "$$value", { $size: "$$this" } ] }
}
}
}
]
}
}
}
}
}
])您可以决定在构建筛选条件时使用$allElementsTrue或$anyElementTrue哪个更好。
https://stackoverflow.com/questions/58224308
复制相似问题