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

    评论

报告相同问题?

悬赏问题

  • ¥15 机器学习教材中的例题询问
  • ¥15 求.net core 几款免费的pdf编辑器
  • ¥20 SQL server表计算问题
  • ¥15 C# P/Invoke的效率问题
  • ¥20 thinkphp适配人大金仓问题
  • ¥20 Oracle替换.dbf文件后无法连接,如何解决?(相关搜索:数据库|死循环)
  • ¥15 数据库数据成问号了,前台查询正常,数据库查询是?号
  • ¥15 算法使用了tf-idf,用手肘图确定k值确定不了,第四轮廓系数又太小才有0.006088746097507285,如何解决?(相关搜索:数据处理)
  • ¥15 彩灯控制电路,会的加我QQ1482956179
  • ¥200 相机拍直接转存到电脑上 立拍立穿无线局域网传