Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongo join between two collections

I have two mongo collections:

  1. defn

    "_id" : ObjectId("8570bebcb7db3"), 
    "fields" : [    {      
    "control" : {   "appearance" : "field-list" },  
    "children" : [ {       "bind" : {      "required" : "yes" },   ...
    
  2. data

    "_id" : ObjectId("1570bf18a7db"),
    "defn" : ObjectId("8570bebcb7db3"),
    "data" : {
            "country" : "",
            "age" : 1,
            "age_unit" : "years", 
    },
    "label" : "type"
    

that are joined where defn._id =data.defn

How can I write a query to return data.label for defn._id? The query would be of the form db.defn.find({ data.label where defn._id= "X"})

like image 550
user2002858 Avatar asked May 07 '26 07:05

user2002858


1 Answers

If you're using MongoDB 3.2, the $lookup stage can perform the equivalent of a left outer join.

The documentation provides an example of using this operation here.

Example using your data:

db.defn.insert({
  "_id" : "123456", 
  "some_text" : "main document"
})

db.data.insert( { 
  "defn" : "123456",
  "label" : "data we want to access"
})

db.defn.aggregate( [ 
  { "$lookup" : {
     "from" : "data",
     "localField" : "_id", 
     "foreignField" : "defn",
     "as" : "defns"
    }
  } 
])

// Results:
// { 
//   "_id" : "123456", 
//   "some_text" : "main document", 
//   "defns" : [ { 
//      "_id" : ObjectId("57a2cbbbeb99ff285a1f0893"), 
//      "defn" : "123456", 
//      "label" : "data we want to access" 
//    } ] 
// }
like image 62
Adam Harrison Avatar answered May 10 '26 21:05

Adam Harrison



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!