MongoDB查询子文档数组的第n个元素(变量索引) [英] MongoDB query on n'th element(variable index) of subdocument array

查看:499
本文介绍了MongoDB查询子文档数组的第n个元素(变量索引)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何查询MongoDB中 n 是变量的子文档数组的第 n 个元素? / p>

假设我有以下文件:

  {
list:[
{
a:true,
b:'abc'
},
{
a:false,
b:'def '
},
{
a:true,
b:'ghi'
},
]
}




  1. 查询1:我需要查找所有具有 a的文档:false list 的第一个元素上(即'list.0.a':false


  2. 查询2:我需要找到所有在 a:false 上的文档列表的第二个元素(即<$​​ c $ c>'list.1.a':false )


  3. 查询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 nth 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'
    },
  ]
}

  1. Query 1: I need to find all documents which have a: false on the 1st element of list(i.e. 'list.0.a': false)

  2. Query 2: I need to find all documents which have a: false on the 2nd element of list(i.e. 'list.1.a': false)

  3. Query 3: I need to find all documents which have a: false on the 3rd element of list(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆