gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:54:19 24 4
gpt4 key购买 nike

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

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

然后,做一个 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" }

这有可能吗?

最佳答案

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

关于MongoDB : create a view which is the union of several collections,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43519729/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com