0
Hello,
I have two Collections and want to query the two Collections, like the sql "Join". The relation between the Collections is made as follows:
medico: [{
medicoId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'medicos'
}
}],
And each document will have the following json structure:
[
{
"nome": "clinica teste",
"medico": [
{
"_id": "5e011a3796a5f80e3c0c8d20",
"medicoId": {
"_id": "5dc5eef455a8f61698a0f2cd",
"nome": "Hancho Crutis",
}
},
{
"_id": "5e011a3796a5f80e3c0c8d1f",
"medicoId": {
"_id": "5df16e5746783116709f09b7",
"nome": "camilinha",
}
}
],
}
]
To do "Join" on Mongodb I saw that I have to use Aggregate. I have already researched and tried hard, but without success. The current code I have is this, but always returns me nothing.
Clinicas.aggregate([
{ $lookup: {
from: "medicos",
localField: "medico.medicoId.nome",
foreignField: "nome",
as: 'clinica_nome'
}},
{ $unwind: "$medico"},
{ $match: {'medico.medicoId.nome': "camilinha" }},
Model da Collection CLINICAS
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
nome: {
type: String,
required: true,
maxlength: 50
},
medico: [{
medicoId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'medicos'
}
}],
exame_consulta: [{
exame_consulta_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'exames_consultas'
}
}],
});
module.exports = mongoose.model('clinicas', UserSchema);
MODEL MEDICAL COLLECTION
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const MedicoSchema = new Schema({
nome:{
type: String,
required: true,
maxlength: 80
},
especialidade:{
type: String,
maxlength: 50
},
});
module.exports = mongoose.model('medicos', MedicoSchema);
Post as defined the Collections structure
medicos
andclinicas
.– Andre
@user140828 added. I just removed the other fields to reduce the code.
– augusto francisco