【问题标题】:MongoDB : create a view which is the union of several collectionsMongoDB:创建一个视图,它是几个集合的联合
【发布时间】:2017-04-20 12:36:01
【问题描述】:

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

根据MongoDB Manual,我可以在管道中使用 $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" }

拆分成:

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" }

然后,做一个视图:

查看

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

这样可以吗?

【问题讨论】:

  • 我认为您需要在应用程序级别进行管理。您在这里使用哪种编程语言?
  • 应用程序是用 PHP 和 ZF2 编写的。不过,馆藏还是蛮大的。目前其中有 7000 万份文档,并且每 2 天增长 100 万份。这就是为什么我想尽可能避免在应用程序级别进行管理。

标签: mongodb


【解决方案1】:

这是对 taminov 代码的相同修改。

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'}}
])

【讨论】:

    【解决方案2】:

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

    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'}}
    ])
    

    【讨论】:

      猜你喜欢
      • 2019-06-01
      • 1970-01-01
      • 2021-07-13
      • 2012-12-23
      • 1970-01-01
      • 1970-01-01
      • 2013-10-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多