Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB : create a view which is the union of several collections

Tags:

mongodb

I currently have a collection that i need to split in several smaller collections. Is there a way to make a View containing the union of all my smaller collections ?

According to the MongoDB Manual, i could use the $lookup operator in the pipeline, but it ends up being more like a "join" than an "union".

Here is an example of what i want to do :

Current collection :

{ _id: 1, name: "abc", country: "us" }
{ _id: 2, name: "def", country: "us" }
{ _id: 3, name: "123", country: "de" }
{ _id: 4, name: "456", country: "de" }

Splitting into :

Collection_US

{ _id: 1, name: "abc", country: "us" }
{ _id: 2, name: "def", country: "us" }

Collection_DE

{ _id: 3, name: "123", country: "de" }
{ _id: 4, name: "456", country: "de" }

And then, make a view :

View

{ _id: 1, name: "abc", country: "us" }
{ _id: 2, name: "def", country: "us" }
{ _id: 3, name: "123", country: "de" }
{ _id: 4, name: "456", country: "de" }

Is it possible to do this ?

like image 503
Lupuli Avatar asked Oct 30 '22 08:10

Lupuli


1 Answers

This is the same modified of taminov's code.

db.createView('union_view', 'us', [
  {
    $facet: {
      us: [
        {$match: {}}
      ],
      de: [
        {$limit: 1},
        {
          $lookup: {
            from: 'de',
            localField: '__unexistingfield',
            foreignField: '__unexistingfield',
            as: '__col2'
          }
        },
        {$unwind: '$__col2'},
        {$replaceRoot: {newRoot: '$__col2'}}
      ]
    },
  },
  {$project: {data: {$concatArrays: ['$us', '$de']}}},
  {$unwind: '$data'},
  {$replaceRoot: {newRoot: '$data'}}
])
like image 127
user2382051 Avatar answered Nov 15 '22 09:11

user2382051