mongodb - 如何将现有的字符串数组转换为mongodb中的自定义对象数组?
问题描述
我有一些现有数据,我想更新它,但我无法为此构建查询。我想将字符串数组的选项字段转换和更新为对象数组。有没有可能?
我试过 arrayToObject 但它不起作用下面是我现有的记录:
{
"_id" : ObjectId("5b6455d9c006ae9d142b0da8"),
"PartnerId" : "585938e3d4e9dac9bb2b09c6",
"BusinessID" : NumberLong(98),
"Responses" : [
{
"QID" : 1,
"Order" : 1,
"Question" : "Contact Information 1",
"Options" : [
"First Name",
"Address",
"Email",
"Phone"
],
"Answers" : [
"First Name",
"111, Dublin, California, 94568",
"forms1@vagaro.com",
"111"
]
},
{
"QID" : 8,
"Order" : 6,
"Question" : "Contact Information 2",
"Options" : [
"Address",
"Email"
],
"Answers" : [
"5000 Estate Enighed, Independence, Kansas, 67301"
]
}
]
}
预期结果:
{
"_id" : ObjectId("5b6455d9c006ae9d142b0da8"),
"PartnerId" : "585938e3d4e9dac9bb2b09c6",
"BusinessID" : NumberLong(98),
"Responses" : [
{
"QID" : 1,
"Order" : 1,
"Question" : "Contact Information 1",
"Options" : [
{Option:"First Name", Order:1},
{Option:"Address", Order:2},
{Option:"Email", Order:3},
{Option:"Phone", Order:4}
],
"Answers" : [
"First Name",
"111, Dublin, California, 94568",
"forms1@vagaro.com",
"111"
]
},
{
"QID" : 8,
"Order" : 6,
"Question" : "Contact Information 2",
"Options" : [
{Option:"Address", Order:1},
{Option:"Email" , Order:2}
],
"Answers" : [
"5000 Estate Enighed, Independence, Kansas, 67301"
]
}
]
}
请帮我。谢谢
解决方案
您可以使用如下聚合。我将 mongo shell 与您描述的相同文档一起使用。
db.test.aggregate([
{ $match: {} },
{
$project: {
_id: "$_id",
PartnerId: "$PartnerId",
BusinessID: "$BusinessID",
Responses: {
$map: {
input: "$Responses",
as: 'response',
in: {
"QID" : "$$response.QID",
"Order" : "$$response.Order",
"Question" : "$$response.Question",
"Options" : {
$map: {
input: "$$response.Options",
as: 'option',
in: {
Option: "$$option",
Order: {
$sum: [
{
$indexOfArray: [
"$$response.Options",
"$$option"
]
},
1
]
}
}
}
},
"Answers" : "$$response.Answers"
}
}
}
}
},
{ $out: 'output' }
])
将所需的文档输出到集合output
中。$out
如果您想覆盖/创建另一个集合,您可以检查它并稍后重命名它,或者只是在阶段中指定另一个集合名称。
推荐阅读
- ios - 更新到 Xcode 11 后,Swift WKWebView “获取断言时出错”
- c++ - 虚幻引擎指针问题(不理解)
- javascript - 正确使用 useState 变量
- java - 无法对非静态字段进行静态引用
- azure - 从现有 VPN 创建 Azure 容器
- python - 修复输出的显示
- c# - 关闭日志记录和调试
- python - 已安装 PYSWIP,但尝试导入时显示“模块不存在”
- android - RecycleView List with SearchView is empty after back press
- php - IIS PHP 包含文件停止工作,除非我删除旧的并创建新的