带有条件的MongoDB聚合查找

标签 mongodb mongodb-query aggregation-framework

我有一个名为 article_category 的集合,它存储所有 article_id 属于具有 category_id 的类别,数据格式如下。

集合 1:article_category

{
  "article_id": 2015110920343902,
  "all_category_id": [5,8,10]
}

然后我有另一个名为 article 的集合,其中存储了我所有的帖子

集合 2:文章

{
  "title": "This is example rows in article collection"
  "article_id": 2015110920343902,
},
{
  "title": "Something change"
  "article_id": 2015110920343903,
},
{
  "title": "This is another rows",
  "article_id": 2015110920343904,
}

现在我想使用 regex 执行 MongoDB 查询以查找 title,而 category_id 必须等于 8。这是我的查询,但不起作用。

db.article.aggregate(
{
  $match: 
  {
    title: 
    {
       $regex: /example/
    }
  }
},
{
    $lookup:
       {
         from: "article_category",
         pipeline: [
            { $match: { category_id: 8 } }
         ],
         as: "article_category"
       }
  }
)

以上查询只显示regex匹配但category_id不匹配的记录。

有什么想法吗?

最佳答案

首先是all_category_id,而不是category_id。其次,您不链接文章 - 所有文档都将具有完全相同的 article_category 数组。最后,您可能想要过滤掉没有匹配类别的文章。条件管道应该看起来更像这样:

db.article.aggregate([
  { $match: {
      title: { $regex: /example/ }
  } },
  { $lookup: {
    from: "article_category",
    let: {
      article_id: "$article_id"
    },
    pipeline: [
      { $match: {
          $expr: { $and: [
              { $in: [ 8, "$all_category_id" ] },
              { $eq: [ "$article_id", "$$article_id" ] }
          ] }
      } }
    ],
    as: "article_category"
  } },
  { $match: {
    $expr: { $gt: [
      { $size: "$article_category"},
      0
    ] }
  } }
] )

更新:

如果您不匹配 article_id,则 $lookup 将产生与所有文章相同的 article_category 数组。

假设您的 article_category 集合有另一个文档:

{
  "article_id": 0,
  "all_category_id": [5,8,10]
}

使用 { $eq: [ "$article_id", "$$article_id"] } 在管道中生成的 article_category

[ 
  { 
    "article_id" : 2015110920343902, 
    "all_category_id" : [ 5, 8, 10 ] 
  } 
]

没有:

[ 
  { 
    "article_id" : 2015110920343902, 
    "all_category_id" : [ 5, 8, 10 ] 
  },
  {
    "article_id": 0,
    "all_category_id": [ 5, 8, 10 ]
  }
]

如果您需要后者,那么查找请求会更简单:

db.article.find({ title: { $regex: /example/ } })

db.article_category.find({ all_category_id: 8 })

关于带有条件的MongoDB聚合查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48518215/

相关文章:

c# - 如何让mongo TTL在c#中过期

javascript - 向 MongoDB 插入数据并上传图片问题 enctype ="multipart/form-data"

Mongodb,带条件的$sum

mongodb - 在执行 $unwind 时过滤掉一些值

javascript - Mongo 查询如果字段不存在。如果存在,则必须在一个范围内

mongodb 查询 : $size with $gt returns always 0

javascript - Node.js 和 Backbone.js 的集成

javascript - Meteor 句柄将数据库字段值作为变量返回

mongodb - 比较两个对象数组并检查它们是否具有共同元素

mongodb - 如何比较两个字符串格式时间?