MongoDB:从一个集合中基于另一个集合进行条件选择

MongoDB:从一个集合中基于另一个集合进行条件选择

问题描述:

我对MongoDB还是很陌生,需要帮助,以便根据另一个集合的数据对一个集合进行选择或某种形式的左联接.

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.

我有两个集合,分别是动物和膳食,我想获取在特定日期(比如说20171001)之后最后一次注册膳食的动物,以确定该动物是否仍在活动.

I have two collections, animals and meals, and I want to get the animal(s) that has had it's last registered meal after a certain date (let's say 20171001) to determine if the animal is still active.

collection animals:
{
    name: mr floof,
    id: 12345,
    lastMeal: abcdef
},
{
    name: pluto,
    id: 6789,
    lastMeal: ghijkl
}

collection meals:
{
    id: abcdef,
    created: 20171008,
    name: carrots
},
{
    id: ghijkl,
    created: 20170918,
    name: lettuce
}

因此在这种情况下查询的预期输出为:

So the expected output of the query in this case would be:

{
    name: mr floof,
    id: 12345,
    lastMeal: abcdef
}

由于Floof先生上一顿饭是20171008,即20171001之后.

As Mr Floof has had his last meal 20171008, i.e. after 20171001.

希望我足够清楚,但是如果没有,请不要犹豫.

Hope I was clear enough, but if not, don't hesitate to ask.

您可以在下面的汇总查询中进行尝试.

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
      }
    }
  }
])

更多信息此处.

您可以在$match阶段之后将$project与排除一起使用,以格式化响应以排除联接的字段.类似于{ $project: {"last_meal":0} }

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