MongoDB合并两个相同的架构集合
我正在使用带有node express的mongoDB,我在我的db中有两个名称为“user”和“user_archive”的集合。我想在查询中合并两个集合数据,并希望执行分页。
对于单一集合分页,我使用下面的代码:
user.find(condition)
.select()
.limit(perPage)
.skip(perPage * page)
.sort(sortObject)
.exec(function(err, data)
{
callback(err,data);
});
我想通过合并user和user_archive集合数据来执行分页。
用户集合
{"name":A}
{"name": B}
user_archive集合
{"name":C}
{"name":D}
我需要合并下面的两个集合,然后想要执行分页:
{"name":A}
{"name":B}
{"name":C}
{"name":D}
任何人都可以建议我如何在我的代码中这样做。
回答如下:您可以使用聚合管道。例如
用户集合
{ "_id": "1", "email": "[email protected]", "fullName": "Jon1"},
{ "_id": "2", "email": "[email protected]", "fullName": "Jon2"},
{ "_id": "3", "email": "[email protected]", "fullName": "Jon3"}
邮政集合
{ "_id": "11", "owner": "1", "content": "text1"},
{ "_id": "12", "owner": "2", "content": "text2"},
{ "_id": "13", "owner": "3", "content": "text3"},
.
async function getData (options) {
let query = [];
// merge posts and users
query.push(
{ $lookup: { from: 'posts', localField: '_id', foreignField: 'owner', as: 'posts' } }
);
// pagination
if (options.page && options.size) {
let skip = options.size * (options.page - 1);
query.push(
{ $skip: skip },
{ $limit: options.size }
);
}
return await db.posts.aggregate(query);
}
这个函数的结果将是
{ "_id": "11", "owner": { "_id": "1", "email": "[email protected]", "fullName": "Jon1" }, "content": "text1"},
{ "_id": "12", "owner": { "_id": "2", "email": "[email protected]", "fullName": "Jon2" }, "content": "text2"},
{ "_id": "13", "owner": { "_id": "3", "email": "[email protected]", "fullName": "Jon3" }, "content": "text3"}
例如,如果options = {page:1,size:2},则结果为
{ "_id": "11", "owner": { "_id": "1", "email": "[email protected]", "fullName": "Jon1" }, "content": "text1"},
{ "_id": "12", "owner": { "_id": "2", "email": "[email protected]", "fullName": "Jon2" }, "content": "text2"},