带有条件的 MongoDB 项目数组文档大小 [英] MongoDB Project Array Document Size with Condition
问题描述
假设我有以下文档结构:
Let's say I have the following document structure:
{
"_id": "ID",
"array": [
{
"a": "A",
"b": "B",
"c": {
"x": true,
"y": true,
"z": false
}
},
{
"a": "A",
"b": "B"
},
{
"a": "A",
"b": "B"
"c": {
"s": true
}
}
]
}
我正在尝试进行聚合以提供这种类型的输出:
I am trying to do an aggregation which gives me this type of output:
{
"_id": "ID",
"array": [
{
"a": "A",
"b": "B",
"c": 2
},
{
"a": "A",
"b": "B",
"c": 0
},
{
"a": "A",
"b": "B"
"c": 1
}
]
}
所以我想要做的是,而不是文档 c
,返回以 true
作为值的元素的数量.和示例一样,c
字段不一定存在(在这种情况下我想返回 0),当它存在时,它的子字段不一定与其他 c
数组中的子字段.假设我正在进行聚合:
So what I want to do is to, instead of the document c
, return the number of elements with true
as value. And as in the example, the c
field does not necessarily exist (in which case I want to return 0), and when it does, it's subfields are not necessarily the same as other c
subfields in the array. Let's say I am doing the aggregation:
db.collection.aggregate([
{"$match": {<conditions>}},
{"$project": {
"array.a": 1,
"array.b": 1,
"array.c": <?>,
}}
])
如何在投影中调整 "array.c"
以完成我所追求的?
How can I adjust "array.c"
in the projection to accomplish what I'm after?
推荐答案
至少需要有MongoDB v3.4.4
You need to have at least MongoDB v3.4.4
投影 "array.a": 1
将返回 ["A", "A", "A"]
.由于您的 array
字段是一个数组,我们需要使用 $map
运算符进行迭代.
Projecting "array.a": 1
will return ["A", "A", "A"]
.
Since your array
field is an array, we need to use $map
operator for iteration.
要遍历对象键,我们需要使用 将其转换为数组$objectToArray 运算符.
To iterate over object keys, we need to transform it into array with $objectToArray operator.
"c": { "c": [
"x": true, {k: "x", v: true},
"y": true, -> {k: "y", v: true},
"z": false {k: "z", v: false},
} ]
然后,我们应用 $filter
运算符来获取 v
为 true
的 k:v
对.
Then, we apply $filter
operator to get just the k:v
pairs whose v
is true
.
db.collection.aggregate([
{
$match: {}
},
{
$project: {
array: {
$map: {
input: "$array",
as: "arr",
in: {
a: "$$arr.a",
b: "$$arr.b",
c: {
$size: {
$filter: {
input: {
$objectToArray: {
$ifNull: [
"$$arr.c",
{}
]
}
},
cond: {
$eq: [
"$$this.v",
true
]
}
}
}
}
}
}
}
}
}
])
这篇关于带有条件的 MongoDB 项目数组文档大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!