Aggregation with Mongodb and $lookup

Asked

Viewed 101 times

0

Good morning, I’m trying to fetch data from two different collections with common values using Aggregate and lookup, but when executing the query it returns empty. I did it this way:

db.createCollection("servidoropc")
db.servidoropc.insert({
"nome": "Servidor de ilha de testes 123",
"url": "OPCLabs.KitServer.2",
"ativo": true
});


db.grupocoletores.insert({
"nome": "Grupo de leitura ilha da foca",
"ativo": true,
"intervaloread": 5000,
"serveropcid": "5cd9ce0c5e5cbddb70dc3c61"
})

db.grupocoletores.aggregate([
{
    $lookup:
    {
        from: "servidoropc",
        localField: "serveropcid",
        foreignField: "_id",
        as: "server_opc"
     }
 }

])

Where am I going wrong?

  • You’re still in trouble?

1 answer

0


This Right however you are saving the "serveropcid" as a string and not as Objectid. If using mongoosejs set in schema.

Behold:Lookup with pipeline

Your Object from Collection groupocoletors should look like this:

{
"_id" : ObjectId("5d14c7cd3b15e7369d26f01c"),
"nome" : "Grupo de leitura ilha da foca",
"ativo" : true,
"intervaloread" : 5000,
"serveropcid" : ObjectId("5d14c7a23b15e7369d26f01b")
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.