dongtuo3795 2019-02-02 07:02
浏览 167

如何更新文档中数组中的字段

I have a document with following structure. I want to insert a new file in the array files followed by making all other file status set to "INACTIVE". After inserting, I am trying following code to update other file of the array but it is unable to match.

{
  {
 "id":"fafsahjaf867rwhrbjw",
 "files" : [
            {"name": "123", status:"ACTIVE"},
            {"name": "124", status:"ACTIVE"},
            {"name": "125", status:"ACTIVE"},
            {"name": "126", status:"ACTIVE"},
           ] 
   },
}

    query = bson.M{ "id": productId,
    "files": bson.M{
        "$not": bson.M{"$elemMatch": fileObj}}}

    update = bson.M{
    "$set": bson.M{
        "files.$.status": "INACTIVE",
    },
  }
  • 写回答

1条回答 默认 最新

  • du656637962 2019-02-02 08:51
    关注

    If you have Mongo >= 3.6, here an example to edit all but the last with name 126.

    db.collection.update(
      { "id" : "fafsahjaf867rwhrbjw", "files.name": "126" },
      { "$set": { "files.$[elem].status": "INACTIVE" } },
      { "arrayFilters": [{ "elem.name": {$ne : "126"} }], "multi": true }
    )
    

    Got that solution from How to Update Multiple Array Elements in mongodb

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!