MongoDB:创建一个视图,它是多个集合的并集

Lup*_*uli 6 mongodb

我目前有一个集合,需要将其分成几个较小的集合。有没有办法制作一个包含所有较小集合的并集的视图?

根据MongoDB 手册,我可以在管道中使用$lookup运算符,但它最终更像是“连接”而不是“联合”。

这是我想做的一个例子:

当前收藏:

{ _id: 1, name: "abc", country: "us" }
{ _id: 2, name: "def", country: "us" }
{ _id: 3, name: "123", country: "de" }
{ _id: 4, name: "456", country: "de" }
Run Code Online (Sandbox Code Playgroud)

分为:

收藏_美国

{ _id: 1, name: "abc", country: "us" }
{ _id: 2, name: "def", country: "us" }
Run Code Online (Sandbox Code Playgroud)

收藏_DE

{ _id: 3, name: "123", country: "de" }
{ _id: 4, name: "456", country: "de" }
Run Code Online (Sandbox Code Playgroud)

然后,进行视图:

看法

{ _id: 1, name: "abc", country: "us" }
{ _id: 2, name: "def", country: "us" }
{ _id: 3, name: "123", country: "de" }
{ _id: 4, name: "456", country: "de" }
Run Code Online (Sandbox Code Playgroud)

是否有可能做到这一点 ?

tam*_*nov 0

它非常老套,但适用于小型集合。如果集合很大,您最终可能不得不使用真正的集合。

db.createView('union_view', 'col1', [
{
    $facet: {
        col1: [
            { $match:{}}
        ],
        col2: [
            { $limit:1},
            { $lookup:{
                from: 'col2',
                localField: '__unexistingfield',
                foreignField: '__unexistingfield',
                as: '__col2'
            }},
            { $unwind:'$__col2'},
            { $replaceRoot: {newRoot: '$__col2'}}
        ]  
    },
},
{ $project: { filesFolders: {$setUnion: ['$files', '$folders']}}},
{ $unwind: '$filesFolders' },
{ $replaceRoot: {newRoot: '$filesFolders'}}
])
Run Code Online (Sandbox Code Playgroud)