MongoDB 查询如何返回数组型数据?
PHPz
PHPz 2017-04-22 09:00:42
0
2
769

例如这样的数据:

{
  "name": "Bob"
  "friends": [
    {
      "name": "Lucy",
      "age": 18
    },
    {
      "name": "David",
      "age": 17
    }
  ]
}

我希望返回这样一个 list: ["Lucy", "David"]

其实说白了,我需要用这个返回的结果进行二次查询,比如查询 Lucy 和 David 的信息。

PHPz
PHPz

学习是最好的投资!

reply all(2)
伊谢尔伦

Restrict fields,db.DATA.find({ }, { "name" : 1 })

Peter_Zhu

mongo supports js syntax, so you can use js capabilities to prune data

> db.b.insert({
              "name": "Bob",
              "friends": [
                {
                  "name": "Lucy",
                  "age": 18
                },
                {
                  "name": "David",
                  "age": 17
                }
              ]
            })
            
WriteResult({ "nInserted" : 1 })
> db.b.findOne({name:"Bob"}).friends.map( x => x.name )
[ "Lucy", "David" ]
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template