MongoDB从数组中检索单个值

时间:2018-12-12 01:36:19

标签: arrays mongodb

假设我有这样的文件

{“ id”:“ 1”,“引用”:[“ AD1”,“ AD2”,“ AD3”]}

我想在数组中检索单个值(“ AD1”)。无论如何,我可以用mongodb查询做到这一点?我已经使用了各种方法,但是它将代替我返回整个数组而不是单个单个值。

1 个答案:

答案 0 :(得分:0)

您可以通过$project$filter进行此操作:

db.collection.aggregate([
  {
    $project: {
      references: {
        $filter: {
          input: "$references",
          as: "ref",
          cond: { $eq: [ "AD1", "$$ref" ] }
        }
      }
    }
  }
])

您可以看到它working here

请注意,$filter在mongoDB 3.2和更高版本中可用

相关问题