英文:
Mongodb aggregate to find record that has both value of a boolean
问题
"I have these documents:
[
{
"id": 1,
"condition": true
},
{
"id": 1,
"condition": false
},
{
"id": 2,
"condition": true
}
]
In this case, I want the output to be "id": 1
, since it has condition
as both true
and false
("id": 2
only has condition
as true
, so it does not qualify).
Thank you"
英文:
I have these documents:
[
{
"id": 1,
"condition": true
},
{
"id": 1,
"condition": false
},
{
"id": 2,
"condition": true
},
]
In this case I want the output to be "id": 1
, since it has condition
as both true
and false
("id": 2
only has condition
as true
, so it does not qualify)
Thank you
答案1
得分: 2
以下是翻译好的部分:
一个选项是对于一般情况下的n
个中的m
个条件,可以使用$setIsSubset
:
db.collection.aggregate([
{$group: {
_id: "$id",
conditions: {$addToSet: "$condition"}
}},
{$match: {$expr: {
$setIsSubset: [
[true, false],
"$conditions"
]
}
}},
{$project: {id: 1}}
])
在playground示例中查看它的运行方式。
英文:
One option is to use $setIsSubset
for the generic case of n
out of m
wanted conditions:
db.collection.aggregate([
{$group: {
_id: "$id",
conditions: {$addToSet: "$condition"}
}},
{$match: {$expr: {
$setIsSubset: [
[true, false],
"$conditions"
]
}
}},
{$project: {id: 1}}
])
See how it works on the playground example
答案2
得分: 1
你可以创建一个聚合管道,首先按照 id
进行分组,并获取一个 conditions
数组。然后检查条件数组是否包含 true 和 false,并创建条件存在的字段 cond_true
和 cond_false
。
如果 cond_true
和 cond_false
都为 true,则匹配。
db.collection.aggregate([
{
$group: {
_id: "$id",
conditions: { $push: "$condition" }
}
},
{
$project: {
_id: 0,
id: "$_id",
cond_true: { $in: [ true, "$conditions" ] },
cond_false: { $in: [ false, "$conditions" ] }
}
},
{
$match: { cond_true: true, cond_false: true }
},
{
$project: { id: 1 }
}
])
英文:
you could create an aggregation pipeline in a way first group by id
and get an array of conditions
. then check if the condition array has true and false and create condition existing fields cond_true
,cond_false
.
If both the cond_true
and cond_false
are true
it is a match.
db.collection.aggregate([
{
$group: {
_id: "$id",
conditions: { $push: "$condition" }
}
},
{
$project: {
_id: 0,
id: "$_id",
cond_true: { $in: [ true, "$conditions" ] },
cond_false: { $in: [ false, "$conditions" ] }
}
},
{
$match: { cond_true: true, cond_false: true }
},
{
$project: { id: 1 }
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论