gpt4 book ai didi

mongodb - 如何过滤子文档数组?

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

我有一个结构如下的文档:

{ 
"_id" : ObjectId("564d2702d4c68225cb00726f"),
"list" : [
{
"a" : NumberInt(1),
"test" : "public"
},
{
"a" : NumberInt(2),
"test" : "public"
},
{
"a" : NumberInt(3),
"test" : "public"
},
{
"a" : NumberInt(4),
"test" : "public"
},
{
"a" : NumberInt(5),
"test" : "public"
}
],
"other_fields": ""}

我可以在 (1, 5) 中过滤子文档吗

下面是我的预期结果

{
"_id" : ObjectId("564d2702d4c68225cb00726f"),
"list" : [
{
"a" : NumberInt(1),
"test" : "public"
},
{
"a" : NumberInt(5),
"test" : "public"
}
]}

我尝试使用$elemMatch,但是当我使用$in时,发生错误。

最佳答案

从 MongoDB 3.2 开始,我们可以使用 $filter运营商要有效地做到这一点。在 $filter 的条件表达式中,我们需要使用 $setIsSubset运算符检查给定值是否在数组中。这主要是因为我们不能使用 $in $project 中的查询运算符阶段。

db.collection.aggregate([
{ "$project": {
"list": {
"$filter": {
"input": "$list",
"as": "lst",
"cond": { "$setIsSubset": [ [ "$$lst.a" ], [ 1, 5 ] ] }
}
}
}}
])

从 MongoDB 3.0.x 开始,您需要一种不同的、效率较低的方法,使用 $map运算符 the 和 $setDifference运算符(operator)。

db.collection.aggregate([
{ "$project": {
"list": {
"$setDifference": [
{ "$map": {
"input": "$list",
"as": "lst",
"in": {
"$cond": [
{ "$setIsSubset": [ [ "$$lst.a" ], [ 1, 5 ] ] },
"$$lst",
false
]
}
}},
[false]
]
}
}}
])

关于mongodb - 如何过滤子文档数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37605431/

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