具有条件的Mongodb聚合查找 [英] Mongodb aggregation lookup with conditions
问题描述
我有一个名为article_category
的集合,该集合存储所有article_id
属于category_id
的类别,其数据格式如下.
I have a collection called article_category
which store all article_id
belongs to the category with category_id
with data format like so.
收藏1:article_category
{
"article_id": 2015110920343902,
"all_category_id": [5,8,10]
}
然后我还有一个名为article
的收藏集,可以存储我的所有帖子
Then I have other collection called article
which store all my post
收藏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,
}
现在,我想执行MongoDB查询以找到带有regex
的title
,而category_id
必须等于8
.这是我的查询,但不起作用.
Now I want to perform MongoDB query to find title
with regex
while category_id
must equal to 8
. Here is my query but is not work.
db.article.aggregate(
{
$match:
{
title:
{
$regex: /example/
}
}
},
{
$lookup:
{
from: "article_category",
pipeline: [
{ $match: { category_id: 8 } }
],
as: "article_category"
}
}
)
上面的查询仅显示符合regex
的记录,而不显示符合category_id
的记录.
Above query only show the records which match by regex
but not match by category_id
.
有什么主意吗?
推荐答案
首先,它是all_category_id
,而不是category_id
.其次,您不链接文章-所有文档将具有完全相同的article_category
数组.最后,您可能希望过滤出类别不匹配的文章.条件管道应如下所示:
First of all, it is all_category_id
, not category_id
. Secondly, you don't link articles - all documents will have exactly the same article_category
array. Lastly, you probably want to filter out articles that don't have matched category. The conditional pipeline should look more like this:
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
数组.
If you don't match article_id
, the $lookup
will result with identical article_category
array to all articles.
假设您的article_category
馆藏还有另一个文档:
Let's say your article_category
collection has another document:
{
"article_id": 0,
"all_category_id": [5,8,10]
}
在管道中使用{ $eq: [ "$article_id", "$$article_id" ] }
时,得出的article_category
为
With { $eq: [ "$article_id", "$$article_id" ] }
in the pipeline the resulting article_category
is
[
{
"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 ]
}
]
如果您需要后者,那么查找请求将更简单:
If the later is what you need, it would be way simpler to make to find requests:
db.article.find({ title: { $regex: /example/ } })
和
db.article_category.find({ all_category_id: 8 })
这篇关于具有条件的Mongodb聚合查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!