Retrieve the related objects in MongoDB without a localField











up vote
0
down vote

favorite












I use MongoDB to store Call Detail Records, which consist of A-legs and B-legs.



They are related as follows:




  • All records (A & B-legs) are in the same cdr collection

  • A-legs have a field leg_type that equals to a, B-legs have b of course

  • B-legs have a field a_leg to indicate to what A-leg they belong.


At the moment we retrieve the A-legs we want, then loop through them and for every A-leg we retrieve the related B-legs (can be multiple), so all on the clientside.



I was wondering if I could do that in one query, and apparently you can with $lookup (aggregation). However it seems to be required that you can reference a field on the A-leg in this case, which would be an array of B-legs.

But I don't have that field, and before I spend unnecessary time to have such a field I was wondering if I could do it differently.



For completeness, this is how we retrieve the CDR's now:



    a_legs = mongo_db['cdr'] 
.find({'group_id': group.id, 'leg_type': 'a'})
.sort('times.created', pymongo.DESCENDING)
.limit(50)

for cdr in a_legs:
# Find B-legs
cdr['b_legs'] = mongo_db['cdr']
.find({'a_leg': cdr['call_id'], 'leg_type': 'b'})
.sort('times.created', pymongo.ASCENDING)


So the bottomline question: can we do the above in a single query to MongoDB?



I tried doing it like this:



db.cdr.aggregate([{
$lookup: {
from: "cdr",
localField: "call_id",
foreignField: "a_leg",
as: "b_legs"
}
}])


But it shows me no results.










share|improve this question




























    up vote
    0
    down vote

    favorite












    I use MongoDB to store Call Detail Records, which consist of A-legs and B-legs.



    They are related as follows:




    • All records (A & B-legs) are in the same cdr collection

    • A-legs have a field leg_type that equals to a, B-legs have b of course

    • B-legs have a field a_leg to indicate to what A-leg they belong.


    At the moment we retrieve the A-legs we want, then loop through them and for every A-leg we retrieve the related B-legs (can be multiple), so all on the clientside.



    I was wondering if I could do that in one query, and apparently you can with $lookup (aggregation). However it seems to be required that you can reference a field on the A-leg in this case, which would be an array of B-legs.

    But I don't have that field, and before I spend unnecessary time to have such a field I was wondering if I could do it differently.



    For completeness, this is how we retrieve the CDR's now:



        a_legs = mongo_db['cdr'] 
    .find({'group_id': group.id, 'leg_type': 'a'})
    .sort('times.created', pymongo.DESCENDING)
    .limit(50)

    for cdr in a_legs:
    # Find B-legs
    cdr['b_legs'] = mongo_db['cdr']
    .find({'a_leg': cdr['call_id'], 'leg_type': 'b'})
    .sort('times.created', pymongo.ASCENDING)


    So the bottomline question: can we do the above in a single query to MongoDB?



    I tried doing it like this:



    db.cdr.aggregate([{
    $lookup: {
    from: "cdr",
    localField: "call_id",
    foreignField: "a_leg",
    as: "b_legs"
    }
    }])


    But it shows me no results.










    share|improve this question


























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I use MongoDB to store Call Detail Records, which consist of A-legs and B-legs.



      They are related as follows:




      • All records (A & B-legs) are in the same cdr collection

      • A-legs have a field leg_type that equals to a, B-legs have b of course

      • B-legs have a field a_leg to indicate to what A-leg they belong.


      At the moment we retrieve the A-legs we want, then loop through them and for every A-leg we retrieve the related B-legs (can be multiple), so all on the clientside.



      I was wondering if I could do that in one query, and apparently you can with $lookup (aggregation). However it seems to be required that you can reference a field on the A-leg in this case, which would be an array of B-legs.

      But I don't have that field, and before I spend unnecessary time to have such a field I was wondering if I could do it differently.



      For completeness, this is how we retrieve the CDR's now:



          a_legs = mongo_db['cdr'] 
      .find({'group_id': group.id, 'leg_type': 'a'})
      .sort('times.created', pymongo.DESCENDING)
      .limit(50)

      for cdr in a_legs:
      # Find B-legs
      cdr['b_legs'] = mongo_db['cdr']
      .find({'a_leg': cdr['call_id'], 'leg_type': 'b'})
      .sort('times.created', pymongo.ASCENDING)


      So the bottomline question: can we do the above in a single query to MongoDB?



      I tried doing it like this:



      db.cdr.aggregate([{
      $lookup: {
      from: "cdr",
      localField: "call_id",
      foreignField: "a_leg",
      as: "b_legs"
      }
      }])


      But it shows me no results.










      share|improve this question















      I use MongoDB to store Call Detail Records, which consist of A-legs and B-legs.



      They are related as follows:




      • All records (A & B-legs) are in the same cdr collection

      • A-legs have a field leg_type that equals to a, B-legs have b of course

      • B-legs have a field a_leg to indicate to what A-leg they belong.


      At the moment we retrieve the A-legs we want, then loop through them and for every A-leg we retrieve the related B-legs (can be multiple), so all on the clientside.



      I was wondering if I could do that in one query, and apparently you can with $lookup (aggregation). However it seems to be required that you can reference a field on the A-leg in this case, which would be an array of B-legs.

      But I don't have that field, and before I spend unnecessary time to have such a field I was wondering if I could do it differently.



      For completeness, this is how we retrieve the CDR's now:



          a_legs = mongo_db['cdr'] 
      .find({'group_id': group.id, 'leg_type': 'a'})
      .sort('times.created', pymongo.DESCENDING)
      .limit(50)

      for cdr in a_legs:
      # Find B-legs
      cdr['b_legs'] = mongo_db['cdr']
      .find({'a_leg': cdr['call_id'], 'leg_type': 'b'})
      .sort('times.created', pymongo.ASCENDING)


      So the bottomline question: can we do the above in a single query to MongoDB?



      I tried doing it like this:



      db.cdr.aggregate([{
      $lookup: {
      from: "cdr",
      localField: "call_id",
      foreignField: "a_leg",
      as: "b_legs"
      }
      }])


      But it shows me no results.







      mongodb aggregation






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 9 at 9:32

























      asked Nov 9 at 8:56









      Maarten Ureel

      7619




      7619
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote













          I figured it out with the help of Studio3T which helped me about to construct the query step by step. This is what I ended up with:



          mongo_db['cdr'].aggregate(
          [
          {
          "$match" : {
          "group_id" : 585,
          "leg_type" : "a"
          }
          },
          {
          "$lookup" : {
          "from" : "cdr",
          "let" : {
          "call_id" : "$call_id"
          },
          "pipeline" : [
          {
          "$match" : {
          "$expr" : {
          "$and" : [
          {
          "$eq" : [
          "$leg_type",
          "b"
          ]
          },
          {
          "$eq" : [
          "$a_leg",
          "$$call_id"
          ]
          }
          ]
          }
          }
          },
          {
          "$project" : {
          "_id" : False,
          "raw" : False,
          "leg_type" : False
          }
          },
          {
          "$sort" : {
          "times.created" : 1
          }
          }
          ],
          "as" : "b_legs"
          }
          },
          {
          "$project" : {
          "_id" : False,
          "raw" : False,
          "leg_type" : False
          }
          }
          ],
          {
          "allowDiskUse" : False
          }
          );


          I needed to use $lookup together with pipeline. I also had to create an index ofcourse on call_id to make it work fast.






          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53222540%2fretrieve-the-related-objects-in-mongodb-without-a-localfield%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote













            I figured it out with the help of Studio3T which helped me about to construct the query step by step. This is what I ended up with:



            mongo_db['cdr'].aggregate(
            [
            {
            "$match" : {
            "group_id" : 585,
            "leg_type" : "a"
            }
            },
            {
            "$lookup" : {
            "from" : "cdr",
            "let" : {
            "call_id" : "$call_id"
            },
            "pipeline" : [
            {
            "$match" : {
            "$expr" : {
            "$and" : [
            {
            "$eq" : [
            "$leg_type",
            "b"
            ]
            },
            {
            "$eq" : [
            "$a_leg",
            "$$call_id"
            ]
            }
            ]
            }
            }
            },
            {
            "$project" : {
            "_id" : False,
            "raw" : False,
            "leg_type" : False
            }
            },
            {
            "$sort" : {
            "times.created" : 1
            }
            }
            ],
            "as" : "b_legs"
            }
            },
            {
            "$project" : {
            "_id" : False,
            "raw" : False,
            "leg_type" : False
            }
            }
            ],
            {
            "allowDiskUse" : False
            }
            );


            I needed to use $lookup together with pipeline. I also had to create an index ofcourse on call_id to make it work fast.






            share|improve this answer

























              up vote
              0
              down vote













              I figured it out with the help of Studio3T which helped me about to construct the query step by step. This is what I ended up with:



              mongo_db['cdr'].aggregate(
              [
              {
              "$match" : {
              "group_id" : 585,
              "leg_type" : "a"
              }
              },
              {
              "$lookup" : {
              "from" : "cdr",
              "let" : {
              "call_id" : "$call_id"
              },
              "pipeline" : [
              {
              "$match" : {
              "$expr" : {
              "$and" : [
              {
              "$eq" : [
              "$leg_type",
              "b"
              ]
              },
              {
              "$eq" : [
              "$a_leg",
              "$$call_id"
              ]
              }
              ]
              }
              }
              },
              {
              "$project" : {
              "_id" : False,
              "raw" : False,
              "leg_type" : False
              }
              },
              {
              "$sort" : {
              "times.created" : 1
              }
              }
              ],
              "as" : "b_legs"
              }
              },
              {
              "$project" : {
              "_id" : False,
              "raw" : False,
              "leg_type" : False
              }
              }
              ],
              {
              "allowDiskUse" : False
              }
              );


              I needed to use $lookup together with pipeline. I also had to create an index ofcourse on call_id to make it work fast.






              share|improve this answer























                up vote
                0
                down vote










                up vote
                0
                down vote









                I figured it out with the help of Studio3T which helped me about to construct the query step by step. This is what I ended up with:



                mongo_db['cdr'].aggregate(
                [
                {
                "$match" : {
                "group_id" : 585,
                "leg_type" : "a"
                }
                },
                {
                "$lookup" : {
                "from" : "cdr",
                "let" : {
                "call_id" : "$call_id"
                },
                "pipeline" : [
                {
                "$match" : {
                "$expr" : {
                "$and" : [
                {
                "$eq" : [
                "$leg_type",
                "b"
                ]
                },
                {
                "$eq" : [
                "$a_leg",
                "$$call_id"
                ]
                }
                ]
                }
                }
                },
                {
                "$project" : {
                "_id" : False,
                "raw" : False,
                "leg_type" : False
                }
                },
                {
                "$sort" : {
                "times.created" : 1
                }
                }
                ],
                "as" : "b_legs"
                }
                },
                {
                "$project" : {
                "_id" : False,
                "raw" : False,
                "leg_type" : False
                }
                }
                ],
                {
                "allowDiskUse" : False
                }
                );


                I needed to use $lookup together with pipeline. I also had to create an index ofcourse on call_id to make it work fast.






                share|improve this answer












                I figured it out with the help of Studio3T which helped me about to construct the query step by step. This is what I ended up with:



                mongo_db['cdr'].aggregate(
                [
                {
                "$match" : {
                "group_id" : 585,
                "leg_type" : "a"
                }
                },
                {
                "$lookup" : {
                "from" : "cdr",
                "let" : {
                "call_id" : "$call_id"
                },
                "pipeline" : [
                {
                "$match" : {
                "$expr" : {
                "$and" : [
                {
                "$eq" : [
                "$leg_type",
                "b"
                ]
                },
                {
                "$eq" : [
                "$a_leg",
                "$$call_id"
                ]
                }
                ]
                }
                }
                },
                {
                "$project" : {
                "_id" : False,
                "raw" : False,
                "leg_type" : False
                }
                },
                {
                "$sort" : {
                "times.created" : 1
                }
                }
                ],
                "as" : "b_legs"
                }
                },
                {
                "$project" : {
                "_id" : False,
                "raw" : False,
                "leg_type" : False
                }
                }
                ],
                {
                "allowDiskUse" : False
                }
                );


                I needed to use $lookup together with pipeline. I also had to create an index ofcourse on call_id to make it work fast.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 9 at 10:56









                Maarten Ureel

                7619




                7619






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53222540%2fretrieve-the-related-objects-in-mongodb-without-a-localfield%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Guess what letter conforming each word

                    Run scheduled task as local user group (not BUILTIN)

                    Port of Spain