MongoDB:根据另一个集合从一个集合中条件选择

时间:2017-12-11 11:56:46

标签: mongodb

我对MongoDB很新,需要帮助根据另一个集合的数据对一个集合进行选择,或者某种左连接。

我有两个收藏品,动物和饭菜,我希望得到在特定日期之后有最后一次登记用餐的动物(让我们说20171001)以确定是否动物仍然活跃。

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
}

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

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

Floof先生的最后一餐是20171008,即20171001之后。

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

2 个答案:

答案 0 :(得分:2)

您可以尝试以下聚合查询。

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

更多信息here

您可以在$project阶段后使用排除$match来格式化排除连接字段的响应。像{ $project: {"last_meal":0} }

这样的东西

答案 1 :(得分:1)

MongoDB支持与$lookup的连接,在您的情况下,您可以使用以下查询: -

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

谢谢!

相关问题