mongo db在nasted数组中选择nasted数组(部分字段)

时间:2019-04-30 03:03:38

标签: node.js mongodb mongoose

mongo db在nasted arry id中选择一个,nasted数组

id : "root"
age : 70,
sons : { id : "son1",
        age : 40
        grandSon : {
          id : "grand1",
          age : 10
      } ,
       { id : "son2",
        age : 40
        grandSon : {
          id : "grand1",
          age : 10
      }
}

我想为grandSon选择儿子(son1,son2)id,年龄执行 我该怎么办?

喜欢这段代码。

let condition: any = { id: grandId}

let select: any = {
id: 1
, "sons.$.id": 1
, "sons.$.age": 1
, "sons.$.grandSon": 0
}
selectOne(~~~)

1 个答案:

答案 0 :(得分:0)

尝试一下。

让它成为文档。

In [49]: a = []                                                                 

In [50]: a.extend(1)                                                            
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-4671950943e4> in <module>
----> 1 a.extend(1)

TypeError: 'int' object is not iterable

查询是

{ "_id" : ObjectId("5cc7d8e88c33e065c56b0883"), "age" : 70.0, "sons" : [ { "id" : "son1", "age" : 40.0, "grandSon" : { "id" : "grand1", "age" : 10.0 } }, { "id" : "son2", "age" : 40.0, "grandSon" : { "id" : "grand1", "age" : 10.0 } } ] }

结果

db.collection.find({},{age:0, 'sons.grandSon': 0 });