MongoDB查询子文档数组的第n个元素(变量索引) [英] MongoDB query on n'th element(variable index) of subdocument array
问题描述
如何查询MongoDB中 n
是变量的子文档数组的第 n
个元素? / p>
假设我有以下文件:
{
list:[
{
a:true,
b:'abc'
},
{
a:false,
b:'def '
},
{
a:true,
b:'ghi'
},
]
}
-
查询1:我需要查找所有具有
a的文档:false
在list
的第一个元素上(即'list.0.a':false
) -
查询2:我需要找到所有在
a:false
上的文档列表
的第二个元素(即<$ c $ c>'list.1.a':false ) -
查询3:我需要查找在
list <的第3个元素上具有
a:false
的所有文档。 / code>(即'list.2.a':false
)
您可以使用 $ expr 以在查询中使用聚合表达式, $ let 定义临时变量, $ arrayElemAt 取数组的第n个元素:
db.collection.find({
$ expr:{
$ let:{
vars:{fst:{$ arrayElemAt:[ $ list,0]}},
in:{$ eq:[ $$ fst.a,false] }
}
}
})
How can I query on the n
th element of a subdocument array in MongoDB where n
is variable?
Suppose, I've documents like bellow:
{
list:[
{
a: true,
b: 'abc'
},
{
a: false,
b: 'def'
},
{
a: true,
b: 'ghi'
},
]
}
Query 1: I need to find all documents which have
a: false
on the 1st element oflist
(i.e.'list.0.a': false
)Query 2: I need to find all documents which have
a: false
on the 2nd element oflist
(i.e.'list.1.a': false
)Query 3: I need to find all documents which have
a: false
on the 3rd element oflist
(i.e.'list.2.a': false
)
You can use $expr to use aggregation expressions in your query, $let to define temporary variable, $arrayElemAt to take nth element of an array:
db.collection.find({
$expr: {
$let: {
vars: { fst: { $arrayElemAt: [ "$list", 0 ] } },
in: { $eq: [ "$$fst.a", false ] }
}
}
})
这篇关于MongoDB查询子文档数组的第n个元素(变量索引)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!