Phorce
Phorce

Reputation: 4652

MongoDB - One to many relationships

I am using MongoDB and I have the following structure:

websites

and

seo_keywords

So a document would look like the following:

{
    "_id" : ObjectId("58503934034b512b419a6eab"),
    "website" : "https://www.google.com",
    "keywords" : [ 
        "testing", 
        "search", 
        "engine"
    ]
} 

And in posts contains a collection:

{
    "_id" : ObjectId("5873656cf632580b98e889b4"),
    "position" : 2,
    "keyword" : "search",
    "found_url" : "https://google.com/"
}

I want to be able to link these two together, so then I can query all of the seo_keywords for websites that are by google

What is the best / efficient way to do this? I have read that the following way could achieve this:

{
        "_id" : ObjectId("5873656cf632580b98e889b4"),
        "position" : 2,
        "keyword" : "search",
        "found_url" : "https://google.com/",

        "website" : [
            "_id" : ObjectId("58503934034b512b419a6eab"), 
            "website" : "https://www.google.com",
            "keywords" : [ 
                "testing", 
                "search", 
                "engine"
            ]
        ]
    }

But is this the most efficient way of doing this? Can I not link the documents together by just using an ID or the actual website?

Upvotes: 0

Views: 80

Answers (1)

Dineshaws
Dineshaws

Reputation: 2083

We can try with $lookup as it provides joining in MongoDB 3.2+, if our relational key is similar in both collections.

db.posts.aggregate([
    {
      $lookup:
        {
          from: "websites",
          localField: "found_url",
          foreignField: "website",
          as: "post_websites"
        }
   }
])

Upvotes: 1

Related Questions