MongoDB: Conditional select from one collection based on another collection

后端 未结 2 1877
广开言路
广开言路 2021-01-29 02:22

I\'m fairly new to MongoDB and need help doing a select, or perhaps some sort of left join, on one collection based on another collection\'s data.

I have two collections

相关标签:
2条回答
  • 2021-01-29 02:50

    MongoDB supports joins with $lookup , In your case you can use query like:-

        db.animals.aggregate([
        {
          $lookup:
            {
              from: "meals",
              localField: "lastMeal",
              foreignField: "id",
              as: "last_meal"
            }
       },
      {
       $match: { 
              "created" : {
                    $gt: "date" //your date format
              }
           } 
     }
    ])
    

    thanks !

    0 讨论(0)
  • 2021-01-29 02:51

    You can try below aggregation query.

    db.animals.aggregate([ [
      {
        "$lookup": {
          "from": "meals",
          "localField": "lastMeal",
          "foreignField": "id",
          "as": "last_meal"
        }
      },
      {
        "$unwind": "$last_meal"
      },
      {
        "$match": {
          "last_meal.created": {
            "$gt": 20171001
          }
        }
      }
    ])
    

    More info here.

    You can use $project with exclusion after $match stage to format the response to exclude joined fields. Something like { $project: {"last_meal":0} }

    0 讨论(0)
提交回复
热议问题