mongodb更新数组中的单个对象

时间:2018-11-27 22:54:16

标签: mongodb express mongoose nosql mongodb-query

如何通过规则查询更新对象数组中的单个对象是该对象必须在具有translation_key ==作为输入的文档中读取,并且我必须读取对象,并且对象必须具有相同的语言(id),否则我必须创建新对象。 (mongodb,猫鼬)

语言为必填项,翻译时必须使用统一语言

{
    "_id" : ObjectId("5bfd5324725fb12bc4863cd8"),
    "deleted" : false,
    "deleted_at" : null,
    "noAuth" : false,
    "hidden" : false,
    "translation_key" : "Standard",
    "translation_type" : "text",
    "translation" : [ 
        {
            "system" : {
                "android" : false,
                "ios" : false,
                "web" : false,
                "api" : false
            },
            "language" : ObjectId("5bf52e06edb9902e2113d8b3"),
            "text":'',
            "active" : false,
            "prepared_string" : false,
            "_id" : ObjectId("5bfd910c2998d929644abd90"),
            "params" : []
        }, 
        {
            "system" : {
                "android" : false,
                "ios" : false,
                "web" : true,
                "api" : false
            },
            "active" : false,
            "prepared_string" : false,
            "_id" : ObjectId("5bfdb5d22998d929644ac2af"),
            "language" : ObjectId("5bf52e06edb9902e6471d8c1"),
            "text" : "Standard",
            "app_version" : "2.0",
            "params" : []
        }
    ],
    "create_date" : ISODate("2018-11-27T14:22:28.635Z"),
    "update_date" : ISODate("2018-11-27T14:22:28.635Z"),
    "__v" : 3
}

1 个答案:

答案 0 :(得分:1)

Model.findOneAndUpdate(
            {
              _id: "document_id",
              "translation.language": "languageId",
            },
            {
              $set: {
                "translation.$.text: "text",
                "translation.$.active": "status",
                "translation.$.system.android" : true
            },
            { new: true, upsert: true, }
          )
          .lean();