有一个名为$expr 的运算符允许您在查询语言中使用聚合表达式。这非常方便
在这里,您需要在查找查询中使用聚合运算符。
将您的查询分解成块以便理解,让我们进行检查
subdocuments.documentId = documents.id
在 mongo 中,这意味着迭代 subdocuments 数组搜索满足上述条件的子文档,可以使用以下方式表示
$filter:
{
'$filter': {
'input': '$subdocuments',
'cond': { '$eq': ['$$this._id', '$_id'] }
}
}
计数位通常用$size 运算符表示,因此从上面获取结果,此查询
count(select * from subdocuments where subdocuments.documentId = documents.id)
被翻译成表达式
{
'$size': {
'$filter': {
'input': '$subdocuments',
'cond': { '$eq': ['$$this._id', '$_id'] }
}
}
}
使用比较运算符$gt满足条件
where count(select * from subdocuments where subdocuments.documentId = documents.id) > 5
作为
{
'$gt': [
{ '$size': {
'$filter': {
'input': '$subdocuments',
'cond': { '$eq': ['$$this._id', '$_id'] }
}
} },
5
]
}
对于相等性,用$eq 显示是微不足道的
{
'$eq': [
{ '$size': {
'$filter': {
'input': '$subdocuments',
'cond': { '$eq': ['$$this._id', '$_id'] }
}
} },
5
]
}
然后可以将上述内容与find() 查询一起使用 $expr as
db.collection.find({
'$expr': {
'$eq': [
{ '$size': {
'$filter': {
'input': '$subdocuments',
'cond': { '$eq': ['$$this._id', '$_id'] }
}
} },
5
]
}
})
分别使用sort()和limit()游标方法进行排序和限制
db.collection.find({
'$expr': {
'$eq': [
{ '$size': {
'$filter': {
'input': '$subdocuments',
'cond': { '$eq': ['$$this._id', '$_id'] }
}
} },
5
]
}
}).sort({ '_id': -1 }).limit(1)
这个查询也有一个聚合变体。使用aggregation framework,管道中使用的表达式是相似的。
查找部分在$match 管道步骤中完成:
db.collection.aggregate([
{ '$match': {
'$expr': {
'$eq': [
{ '$size': {
'$filter': {
'input': '$subdocuments',
'cond': { '$eq': ['$$this._id', '$_id'] }
}
} },
5
]
}
} }
])
排序和限制分别在$sort 和$limit 管道阶段内进行管道传输
db.collection.aggregate([
{ '$match': {
'$expr': {
'$eq': [
{ '$size': {
'$filter': {
'input': '$subdocuments',
'cond': { '$eq': ['$$this._id', '$_id'] }
}
} },
5
]
}
} },
{ '$sort': { '_id': 1 } },
{ '$limit': 1 }
])