MongoDB:基于另一个集合从一个集合中进行条件选择 [英] MongoDB: Conditional select from one collection based on another collection

查看:21
本文介绍了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} }

这篇关于MongoDB:基于另一个集合从一个集合中进行条件选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆