Mongodb 无法将_id字段添加到Mlab中的mongo子文档中

Mongodb 无法将_id字段添加到Mlab中的mongo子文档中,mongodb,mlab,Mongodb,Mlab,在我的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, othe

在我的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”字段,我想取消设置,但我的查询不起作用

  • 我想在不存在的地方添加一个_idobjectid字段。目前有些人有,有些人没有

  • 我尝试了许多查询,但似乎都不起作用。例如:

    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);
    });
    

    这对你来说应该很好

    db.droplets4.updateMany( { 
            "questions._id" : null
        },{ $set: {"questions.$._id": new ObjectId()}},{"multi": true, "upsert": true})
    

    因为您的意思是
    .updateMany({“questions.”id:{“$exists”:false}},{…
    。位置运算符用于“update”文档中,而不是“query”本身。您还应该注意,位置运算符也仅与数组中的“first”匹配索引位置匹配。为了更新“all array elements”如果缺少信息,您实际上需要一种形式的“循环”来更新。的“更好的答案”中描述了这一点。请注意,“大多数投票”在本例中并不特别意味着“更好”。感谢您的回答。这正在使用:db.droplets4.updateMany({“questions.id”:{$exists:true},{$unset:{“questions.$.id”:“}}”)但我在尝试添加id时仍会遇到错误。是的,您是对的,它每次只更新第一个id。我将查看您的链接。