gpt4 book ai didi

mongodb - 如何选择包含在值数组中的数组项的文档?

转载 作者:可可西里 更新时间:2023-11-01 10:27:55 25 4
gpt4 key购买 nike

我在 mongodb (3.0) 中有集合:

{
_id: 1,
m: [{_id:11, _t: 'type1'},
{_id:12, _t: 'type2'},
{_id:13, _t: 'type3'}]
},
{
_id: 2,
m: [{_id:21, _t: 'type1'},
{_id:22, _t: 'type21'},
{_id:23, _t: 'type3'}]
}

我想找到具有 m 个属性的文档,其中 m._t 包含 ['type1', 'type2']。

像这样:

{
_id: 1,
m: [{_id:11, _t: 'type1'},
{_id:12, _t: 'type2'}]
},
{
_id: 2,
m: [{_id:21, _t: 'type1'}]
}

我尝试使用 $ 和 $elemMatch,但无法获得所需的结果。如何做到这一点,使用 find()?请帮帮我!谢谢!

最佳答案

因为$elemMatch运算符限制了查询结果中m数组字段的内容只包含第一个元素匹配$elemMatch条件,下面只会返回第一个匹配元素的数组

{
"_id" : 11,
"_t" : "type1"
}

{
"_id" : 21,
"_t" : "type1"
}

使用$elemMatch投影查询:

db.collection.find(
{
"m._t": {
"$in": ["type1", "type2"]
}
},
{
"m": {
"$elemMatch": {
"_t": {
"$in": ["type1", "type2"]
}
}
}
}
)

结果:

/* 0 */
{
"_id" : 1,
"m" : [
{
"_id" : 11,
"_t" : "type1"
}
]
}

/* 1 */
{
"_id" : 2,
"m" : [
{
"_id" : 21,
"_t" : "type1"
}
]
}

您可以采用的一种方法是 aggregation framework ,其中您的管道将包含一个 $match 运算符,类似于上面用于过滤初始文档流的查找查询。下一个流水线步骤将是关键的 $unwind 运算符,它“拆分”数组元素以使用另一个 $match 运算符进一步简化,然后是最终的 $group 使用累加器运算符 $push 恢复原始数据结构的管道。

下面说明了这个路径:

db.collection.aggregate([
{
"$match": {
"m._t": {
"$in": ["type1", "type2"]
}
}
},
{
"$unwind": "$m"
},
{
"$match": {
"m._t": {
"$in": ["type1", "type2"]
}
}
},
{
"$group": {
"_id": "$_id",
"m": {
"$push": "$m"
}
}
}
])

示例输出:

/* 0 */
{
"result" : [
{
"_id" : 2,
"m" : [
{
"_id" : 21,
"_t" : "type1"
}
]
},
{
"_id" : 1,
"m" : [
{
"_id" : 11,
"_t" : "type1"
},
{
"_id" : 12,
"_t" : "type2"
}
]
}
],
"ok" : 1
}

关于mongodb - 如何选择包含在值数组中的数组项的文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31835982/

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