[英]MongoDB: update nested value in a collection based on existing field value
如果它们的类型是字符串,我想在整个集合中更新嵌套的_id。
如果我有看起来像这样的物体...
user : {
_id: ObjectId('234wer234wer234wer'),
occupation: 'Reader',
books_read: [
{
title: "Best book ever",
_id: "123qwe234wer345ert456rty"
},
{
title: "Worst book ever",
_id: "223qwe234wer345ert456rty"
},
{
title: "A Tail of Two Cities",
_id: ObjectId("323qwe234wer345ert456rty")
}
]
}
我想将_Ids的类型从字符串更改为ObjectId
我会怎么做。
我过去曾经做过“ this” ...但是这正在处理非嵌套项目-我需要更改嵌套值
db.getCollection('users')
.find({
$or: [
{occupation:{$exists:false}},
{occupation:{$eq:null}}
]
})
.forEach(function (record) {
record.occupation = 'Reader';
db.users.save(record);
});
任何帮助-我试图避免在应用服务器上编写一系列循环来进行数据库调用-所以我希望直接在'mongo'中寻找一些东西
在引用现有字段时,没有办法(非$rename
)对文档进行更新操作-MongoDB:使用同一文档中的数据更新文档
因此,您需要编写一个脚本(类似于使用find
& each
发布的脚本),以使用正确的_id类型重新创建这些文档。 要查找要更新的子文档,可以使用$type
运算符。 诸如db.coll.find({nestedField._id: {$type: 'string' }})
应该找到所有包含不良子文档的完整文档,或者您可以使用$match
和$unwind
进行聚合查询,仅获取子文档
db.coll.aggregate([
{ $match: {'nestedField._id': {$type: 'string' }}}, // limiting to documents that have any bad subdocuments
{ $unwind: '$nestedField'}, // creating a separate document in the pipeline for each entry in the array
{ $match: {'nestedField._id': {$type: 'string' }}}, // limiting to only the subdocuments that have bad fields
{ $project: { nestedId: 'nestedField._id' }} // output will be: {_id: documentedId, nestedId }
])
我试图避免在应用服务器上编写一系列循环来进行数据库调用-所以我希望直接在'mongo'中寻找一些东西
您可以直接在mongo上运行js代码,以避免进行api调用,但是我认为没有任何方法可以避免循环遍历文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.