简体   繁体   English

两个集合的聚合数组 mongodb

[英]aggregate array of two collections mongodb

I have two collections: Clinicas and Medicos .我有两个集合: ClinicasMedicos Clinicas can have a lot of Medicos . Clinicas可以有很多Medicos The relation was made this way:关系是这样建立的:

medico: [{
    medicoId: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'medicos'
    }
  }],

And I will have the following json structure:我将有以下 json 结构:

[
    {
        "nome": "clinica teste",
        "medico": [
            {
                "_id": "5e011a3796a5f80e3c0c8d20",
                "medicoId": {
                    "_id": "5dc5eef455a8f61698a0f2cd",
                    "nome": "Hancho Crutis",
                }
            },
            {
                "_id": "5e011a3796a5f80e3c0c8d1f",
                "medicoId": {
                    "_id": "5df16e5746783116709f09b7",
                    "nome": "camilinha",
                }
            }
        ],
    }
]

What I want is to make a "join" of these data.我想要的是对这些数据进行“连接”。 After a long research, I got this code but the response is always empty.经过长时间的研究,我得到了这段代码,但响应始终为空。 Can someone tell me what am I doing wrong?有人能告诉我我做错了什么吗?

Clinicas.aggregate([
        { $unwind: "$medico"},   

        { $lookup: {
            from: "medicos",
            localField: "medicoId._id",
            foreignField: "_id",
            as: 'nome'
        }},

        { $match: {"medicoId._id": "5df16e5746783116709f09b7"}},       

    ])

You need to convert in ObjectId,您需要在 ObjectId 中进行转换,

var mongoose = require('mongoose');

Clinicas.aggregate([
    { $unwind: "$medico" },

    {
        $lookup: {
            from: "medicos",
            localField: "medicoId._id",
            foreignField: "_id",
            as: 'nome'
        }
    },

    { $match: { "medicoId._id": mongoose.Types.ObjectId('5df16e5746783116709f09b7') } },

])

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

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