简体   繁体   English

MongoDB从数组中检索单个值

[英]MongoDB Retrieve single value from array

Assuming that if i have such document 假设如果我有这样的文件

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

I would like to retrieve single value ("AD1") within the array. 我想在数组中检索单个值(“ AD1”)。 is there anyway that i can do that with mongodb query? 无论如何,我可以用mongodb查询做到这一点? i have use various way but that it would instead return me the whole array instead of individual single value. 我已经使用了各种方法,但是它将代替我返回整个数组而不是单个单个值。

You can do this via $project and $filter : 您可以通过$project$filter做到这一点:

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

You can see it working here 你可以看到它在这里工作

Note however that $filter is available in mongoDB 3.2 version and higher 但是请注意, $filter在mongoDB 3.2和更高版本中可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM