MongoDB: Conditional select from one collection based on another collection

后端 未结 2 1878
广开言路
广开言路 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: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} }

提交回复
热议问题