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

查看:378
本文介绍了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天全站免登陆