【问题标题】:How to replace all the elements of an array in a MongoDB document?如何替换 MongoDB 文档中数组的所有元素?
【发布时间】:2016-01-02 05:09:47
【问题描述】:

如果我有一个新的字符串数组 (arr),并且想用这个数组替换 mongoDB 文档的字符串组件访问的 mongoDB 文档中的数组,我该怎么做?

这是我目前所拥有的,但它不起作用:

Posts.update({user: userVar},{ tags: arr }});

目前在网上看到的东西好像真的很别扭,好像需要2个步骤。

【问题讨论】:

    标签: mongodb meteor mongoose database


    【解决方案1】:

    这应该是一个直接的更新。

     Posts.update({user: userVar}, {$set: { tags: arr }});
    

    mongo

    > db.so34562815.find( ).pretty()
    {
        "_id" : ObjectId("56875d7a6a21dd6b99743439"),
        "user" : "test",
        "tags" : [
            "one",
            "two"
        ]
    }
    
    > arr = ['three']
    [ "three" ]
    
    > db.so34562815.update({user:'test'},{$set: {tags:arr}})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    
    > db.so34562815.find( ).pretty()
    {
        "_id" : ObjectId("56875d7a6a21dd6b99743439"),
        "user" : "test",
        "tags" : [
            "three"
        ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2021-12-24
      • 1970-01-01
      相关资源
      最近更新 更多