MongoDB合并两个相同的架构集合

时间:2019-02-19 10:22:25

标签: node.js mongodb

我正在将mongoDB与node express一起使用,并且我的数据库中有两个集合,名称分别为“ 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}

任何人都可以在我的代码中建议我该怎么做。

1 个答案:

答案 0 :(得分:0)

您可以使用聚合管线。 例如

用户集合

{ "_id": "1", "email": "test1@gmail.com", "fullName": "Jon1"},
{ "_id": "2", "email": "test2@gmail.com", "fullName": "Jon2"},
{ "_id": "3", "email": "test3@gmail.com", "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": "test1@gmail.com", "fullName": "Jon1" }, "content": "text1"},
{ "_id": "12", "owner": { "_id": "2", "email": "test2@gmail.com", "fullName": "Jon2" }, "content": "text2"},
{ "_id": "13", "owner": { "_id": "3", "email": "test3@gmail.com", "fullName": "Jon3" }, "content": "text3"}

例如,如果options = {page:1,size:2},结果将为

{ "_id": "11", "owner": { "_id": "1", "email": "test1@gmail.com", "fullName": "Jon1" }, "content": "text1"},
{ "_id": "12", "owner": { "_id": "2", "email": "test2@gmail.com", "fullName": "Jon2" }, "content": "text2"},