是否有mongoDB runCommand returns 多个集合?
Is there a mongoDB runCommand that returns multiple collections?
我正在尝试编写一个 mongoDB runCommand,它 return 多个集合使用一个命令。
我已经在 runCommand 中成功使用了 find 命令,但我不确定如何 return 多次查找搜索。重要的是它们不合并。
类似于:
db.runCommand(
[{
"find": "venues"
},
{
"find": "guests"
}]
)
理想情况下,结果将遵循类似于此结构的内容:
{
"venues": {all venue data from mongo},
"guests": {all guest data from mongo}
}
据我所知,这个问题与 runCommand
没有任何共同之处。RunCommand
只是运行一个 single 命令。您真正需要的是使用 unionWith 聚合阶段和可能的一些 post 数据处理。
db.orders.aggregate([
{
$unionWith: {
coll: "inventory",
pipeline: [
{
$addFields: {
"fromInventory": 1 // add a flag that shows that this data is not from original collection
}
}
]
}
},
{
"$group": {
"_id": "$fromInventory",
"content": {
"$addToSet": "$$ROOT"
}
}
},
{
"$project": {
"content": 1, // also it's possible to exclude a flag from output via: `"content.fromInventory": 0,` instead `"content" : 1`
_id: 0
}
}
])
参见here。您可能需要进一步改进此结果,例如 $replaceRoot
我正在尝试编写一个 mongoDB runCommand,它 return 多个集合使用一个命令。
我已经在 runCommand 中成功使用了 find 命令,但我不确定如何 return 多次查找搜索。重要的是它们不合并。
类似于:
db.runCommand(
[{
"find": "venues"
},
{
"find": "guests"
}]
)
理想情况下,结果将遵循类似于此结构的内容:
{
"venues": {all venue data from mongo},
"guests": {all guest data from mongo}
}
据我所知,这个问题与 runCommand
没有任何共同之处。RunCommand
只是运行一个 single 命令。您真正需要的是使用 unionWith 聚合阶段和可能的一些 post 数据处理。
db.orders.aggregate([
{
$unionWith: {
coll: "inventory",
pipeline: [
{
$addFields: {
"fromInventory": 1 // add a flag that shows that this data is not from original collection
}
}
]
}
},
{
"$group": {
"_id": "$fromInventory",
"content": {
"$addToSet": "$$ROOT"
}
}
},
{
"$project": {
"content": 1, // also it's possible to exclude a flag from output via: `"content.fromInventory": 0,` instead `"content" : 1`
_id: 0
}
}
])
参见here。您可能需要进一步改进此结果,例如 $replaceRoot