mongodb - mongodb $unwind 用于非理想嵌套文档
问题描述
我知道下面的 mongodb 文档可能不是一个理想的结构,但是有什么办法可以解除它$rounds.round_values
吗?
我已经尝试过aggregate([{"$unwind": "$rounds"}])
,或者"$rounds.round_values"
但这似乎不起作用。非常感谢任何建议。
{
"_id" : ObjectId("60bea750c26a1c7095387d00"),
"rounds" : [
{
"round_number" : "0",
"round_values" : {
"max_player_pot" : "0.25",
"pot_multiple" : "0.625",
},
{
"round_number" : "1",
"round_values" : {
"max_player_pot" : "0.0",
"pot_multiple" : "0.0",
}
],
"GameID" : "392124717",
"ComputerName" : "awdfadf",
}
预期输出:
{
"max_player_pot" : "0.25",
"pot_multiple" : "0.625",
"GameID" : "392124717",
"ComputerName" : "awdfadf",
},
{
"max_player_pot" : "0.0",
"pot_multiple" : "0.0",
"GameID" : "392124717",
"ComputerName" : "awdfadf",
}
解决方案
$unwind
解构rounds数组$project
显示必填字段
db.collection.aggregate([
{ $unwind: "$rounds" },
{
$project: {
GameID: 1,
ComputerName: 1,
max_player_pot: "$rounds.round_values.max_player_pot",
pot_multiple: "$rounds.round_values.pot_multiple"
}
}
])
更动态的方法,
$mergeObjects
合并来自根和round_values
对象的必填字段$replaceRoot
将上述合并对象替换为根
db.collection.aggregate([
{ $unwind: "$rounds" },
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{
GameID: "$GameID",
ComputerName: "$ComputerName"
},
"$rounds.round_values"
]
}
}
}
])
推荐阅读
- javascript - 使用另一个字符串数组过滤数组的内容
- inno-setup - Inno Setup - 在消息框打开和关闭时为消息框设置动画
- django - 为什么我的 Python Django url 不起作用?
- c++ - 使用函数 decimal 仅将输入的小数返回为 double C++
- spring-boot - 如何在 Spring 应用程序中修改有效负载响应数据?
- android - Flutter - Crashlytics 仍在 Firebase 中加载
- flutter - 颤振中的showDialog在iOS的发布版本中不起作用
- python - 使用 plotly 绘制曲面图
- swift - SwiftUI 在 NavigationView 中添加个人警报视图,后退按钮不适用于 Xcode 12 iOS14
- python - 训练具有可变输入大小的 keras 模型