MongoDB聚合限制查询 [英] MongoDB Aggregation Limit Lookup
问题描述
我正在PyMongo中使用$ lookup成功加入"两个集合(此方法有效).我遇到的问题是,当我加入的第二个集合返回所有记录时,该大小可能超过BSON文档的大小.
I am using $lookup in PyMongo to successfully "join" two collections (this works). I am having a problem where the second collection I am joining in may exceed the BSON document size when it returns all of the records.
我希望使用$ limit来限制"match_docs"下允许加入的记录数,例如:每个obj_id的评论"中最多可以有100条记录:
I am looking to use $limit to limit the number of records that are allowed to join under "match_docs" eg: 100 records maximum from "comments" per obj_id:
db.indicators.aggregate([
{
"$lookup": {
"from": "comments",
"localField": "_id",
"foreignField": "obj_id",
"as": "match_docs"
}
}
])
我尝试了各种类型的$ limit,它似乎仅限制了整个结果的总数,而不仅限于联接.
I've tried various types of $limit, and it seems to only limit the total number of results overall, not just for the join.
推荐答案
从MongoDB 3.6开始,您可以使用不相关的子查询来限制查找:
Starting from MongoDB 3.6 you can use uncorrelated subqueries to limit the lookup:
db.indicators.aggregate([
{ $lookup: {
from: 'comments',
as: 'match_docs',
let: { indicator_id: '$_id' },
pipeline: [
{ $match: {
$expr: { $eq: [ '$obj_id', '$$indicator_id' ] }
} },
// { $sort: { createdAt: 1 } }, // add sort if needed (for example, if you want first 100 comments by creation date)
{ $limit: 100 }
]
} }
])
这篇关于MongoDB聚合限制查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!