【问题标题】:How to make query that find inside of find in mongodb如何在mongodb的find中进行查询
【发布时间】:2020-04-03 09:18:39
【问题描述】:

我在 Mongodb 中有如下文档。

{
  "vatInfo":{
        "company": "apple"
  },
  "type": "manager",
  "parent": "123"
}

我在同一个集合中有另一个文档,如下所示。

{
  "type": "member",
  "parentId": "123",
  "id": "3"
}

当我创建client.find({id: 3, type: 'member'}) 时,我想得到它,它会在 find 中自动找到 vatInfo。

{
  "type": "member",
  "parentId": "123",
  "id": "3",
  "vatInfo":{
    "company": "apple"
  },
}

我应该如何为这个发现进行聚合?我不想双重查找。 非常感谢您阅读它。

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    您可以为此使用聚合管道。

    $match - 查找父文档。

    $lookup - 加入来自其他集合的文档。

    $project - 修改结果的结构。

    // collection `client`
    {
        "vatInfo":{ "company": "apple" },
        "type": "manager",
        "parent": "123"
    },
    {
        "type": "member",
        "parentId": "123",
        "id": "3"
    }
    
    // query example
    db.getCollection('client').aggregate([
        { $match: { 'id': '3', 'type': 'member' } },
        {
            $lookup: {
                from: 'client',
                localField: 'parentId',
                foreignField: 'parent',
                as: 't01'
            }
        },
        {
            $project: {
                '_id': 0,
                'type': 1,
                'parentId': 1,
                'id': 1,
                'vatInfo': { $arrayElemAt: [ "$t01.vatInfo", 0 ] }
            }
        }
    ])
    
    // result
    {
        "type" : "member",
        "parentId" : "123",
        "id" : "3",
        "vatInfo" : {
            "company" : "apple"
        }
    }
    

    【讨论】:

    • 据我了解,这两个文档都在同一个集合中。
    • @SuleymanSah 感谢您的关注(不知何故我错过了),我已经更新了我的答案
    【解决方案2】:

    要添加另一个文档的字段,您可以在 Mongoose 中使用 populate :

    为此,您需要在客户端文档和父文档之间的架构中引用:

    const clientSchema = Schema({
      [...]
      parentId: { type: Schema.Types.ObjectId, ref: 'ParentCollection' }
    });
    

    然后,您可以在代码中的任何位置使用填充:

    client.findOne({id: 3, type: 'member'}).populate('parentId');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-04
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      相关资源
      最近更新 更多