简体   繁体   中英

MongoDB Using aggregate and $lookup to simulate a JOIN of collections in Mongo

So I have collections projects which has field contacts.envCon.$id :

     {
       "contacts" : {
            ...
            "envCon" : {
                "$ref" : "contacts",
                "$id" : ObjectId("5807966090c01f4174cb1714") <---- NOTICE!!!
            }
            ...
        }
   }

On contacts collection Object with id Example12345 looks like this:

{
    "_id" : ObjectId("5807966090c01f4174cb1714"),
    "name" : "Terracon"
}

So I tried the following $lookup from aggregation framework:

db.getCollection('projects').aggregate([
    {
            $lookup:{
                    from: "contacts",
                    localField: "contacts.envCon.id",
                    foreignField: "id",
                    as: "example"
            }
    }
]);

But it is not doing the JOIN what am I missing? how to do lookups between 2 collections using contacts.envCon.id from projects and _id from contacts.

I'm using meteor just in case.

I'm not sure what is going on with your ObjectId values; I'm not even able to insert a field value of ObjectId("Example12345"). The difference in ObjectID values between the two collections is likely what is causing the $lookup to fail.

The aggregation query you provided works in my environment when I let MongoDB generate the _id ObjectID value in "contacts" and store the same value in the "projects" collection.

$ db.projects.find().pretty()
{
    "_id" : ObjectId("580832011b3c40dba2ae6e32"),
    "contacts" : {
        "envCon" : DBRef("contacts", ObjectId("580831d61b3c40dba2ae6e31"))
    }
}

$ db.contacts.find().pretty()
{ "_id" : ObjectId("580831d61b3c40dba2ae6e31"), "name" : "Terracon" }


$ db.getCollection("projects").aggregate([ { "$lookup" : {     "from" : "contacts",      "localField" : "contacts.envCon.id",     "foreignField" : "id",     "as" : "example"   } } ]).pretty()
{
    "_id" : ObjectId("580832011b3c40dba2ae6e32"),
    "contacts" : {
        "envCon" : DBRef("contacts", ObjectId("580831d61b3c40dba2ae6e31"))
    },
    "example" : [
        {
            "_id" : ObjectId("580831d61b3c40dba2ae6e31"),
            "name" : "Terracon"
        }
    ]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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