将第一个数组值复制到 MongoDB 中的另一个字段 [英] Copy first array value to another field in MongoDB
问题描述
我有一个旧的产品列表,将描述存储在索引 [0] 处的数组中.该模型设置为字符串.所以我的计划是提取该值并将其添加到临时字段中.第 2 步是获取该值并将其复制到原始字段.这是我想要修复的错误"产品.
I have an old list of products that store the descriptions in an array at index [0]. The model is set up as a string. So my plan is to extract that value and add it to a temporary field. Step 2 would be to take that value and copy it to the original field. This is the 'wrong' product I want to fix.
{_id : 1 , pDescription : ['great product']},
{_id : 2 , pDescription : ['another product']}
我只想将数组更改为这样的字符串:
All I want to is to change the array to a string like this:
{_id : 1 , pDescription : 'great product'},
{_id : 2 , pDescription : 'another product'}
我试过这个来创建临时描述:
I have tried this to create the temporary description:
Products.aggregate([
{
$match: {
pDescription: {
$type: "array"
}
}
},
{
$set: {
pDescTemp: {
$first: "$pDescription"
}
}
}
]).exec((err, r) => {
// do stuff here
});
该命令在没有 $first
命令的情况下工作正常.错误内容为:MongoError: Unrecognized expression '$first'
The command works fine without the $first
command.
The error reads: MongoError: Unrecognized expression '$first'
感谢您提供有关如何解决此问题的任何提示!谢谢!
Any tips on how to fix this are appreciated! Thanks!
推荐答案
我相信这是您需要更新 pDescription
字段以等于已存储为 <代码>p描述:
I believe this is what you need to update your pDescription
field to be equal to the first element of the array already stored as pDescription
:
db.Products.updateMany({},
[
{
$set: {
pDescription: {
$arrayElemAt: [
"$pDescription",
0
]
}
}
}
])
这篇关于将第一个数组值复制到 MongoDB 中的另一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!