在我的Mlab mongo 3.2数据库中,我有一个如下所示的集合:
{
"_id": {
"$oid": "5752d....87985"
},
"name": "...etation",
"description": null,
"user_id": ".....",
"questions": [
{
"prompt": "The conclusions drawn seemed clear to most researchers, however, others were unconvinced, arguing that everything is open to ____________.",
"answer": "interpretation",
"created_at": "2014-11-09T14:59:38.154",
"updated_at": "2014-11-09T14:59:38.154",
"filled_answer": null
},
{
"id": 922,
"prompt": "His existential quest for Truth is in fact the key to his understanding and ____________ of the Bhagavad-Gītā.",
"answer": "interpretation",
"created_at": "2014-10-03T08:07:40.295",
"updated_at": "2014-10-03T08:07:40.295",
"filled_answer": null
},
}
我正在努力解决的问题子文档存在两个问题:
有时但并非总是存在遗留的“id”字段,我想要取消设置但我的查询无效。
我想添加一个尚未存在的_id ObjectID字段。目前有些人有,有些人没有。
我尝试了很多查询,但似乎都没有。例如:
db.droplets.updateMany({"questions.$._id": { $exists: false }},{ $set: {"questions.$._id": new ObjectId()}},{"multi": true, "upsert": true})
Mongo告诉我“位置操作员没有找到查询所需的匹配”
更新
我已成功找到使用以下脚本删除所有问题的方法:
db.droplets4.find().forEach(function (doc) {
doc.questions.forEach(function (question) {
if (question.id) {
delete question.id
}
});
db.droplets.save(doc);
});
但是同样的策略不适用于添加对象ID。此代码不起作用:
db.droplets4.find().forEach(function (doc) {
doc.questions.forEach(function (question) {
if (!question._id) { question._id = new ObjectId() }
});
db.droplets.save(doc);
});
答案 0 :(得分:0)
这应该适合你
db.droplets4.updateMany( {
"questions._id" : null
},{ $set: {"questions.$._id": new ObjectId()}},{"multi": true, "upsert": true})