【问题标题】:How to update a collection in mongodb如何在 mongodb 中更新集合
【发布时间】:2021-09-16 02:24:23
【问题描述】:

我有一个 json 插入到我的 mongo 集合中。现在我想更新插入到集合中的相同 json,这样我需要使用 id 将新数据元素添加到该集合中,这将较早产生。 例如:

{
 "name":"sam",
 "age":20,
  "_id":""5sq8uye1236g'
 }

如果上面是插入到一个集合中的json,我们在集合中为它生成了_id。 现在我有了一个名为 token 的变量。

var token=12345

现在我想更新上述集合,以便根据其中的 _id 添加此令牌。 集合中要求的格式:

{
"name":"sam",
"age":20,
 "token":12345,
"_id":""5sq8uye1236g'
 } 

我该怎么做?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    使用update 命令。

    您的查询应如下所示

    db.collection.update({_id:'5sq8uye1236g'},{$set :{token :12345});
    

    阅读更多关于更新here

    【讨论】:

    • 谢谢。但在我的收藏中,id 生成为 "_id":{"_str":"5sq8uye1236g"}。我无法更新
    • db.collection.update({_id:{'_str':'5sq8uye1236g'},{$set :{token :12345}); 试试这个。
    • 任何请参考文档。这样的例子很多。
    【解决方案2】:

    截至 2020/2021 年使用 ObjectId()

    通过 Mongo 的 ID 更新时不能使用简单的字符串,需要使用 ObjectId。例如,假设您的 ObjectId 是 xxxxxxxxxxxxx:

    db.mycollection.update({_id:ObjectId('xxxxxxxxxxxxx')},{$set :{token:12345}})
    

    我不能说哪个是最低版本,但我从 v4.2.2 开始对此进行了测试。

    【讨论】:

      【解决方案3】:
      db.<collection_name>.update(
         { _id: 5sq8uye1236g },
         { $set:
            {
              "token": "12345"
            }
         }
      )
      

      https://docs.mongodb.com/manual/reference/operator/update/set/

      【讨论】:

      • 谢谢。但在我的收藏中,id 生成为 "_id":{"_str":"5sq8uye1236g"}。我无法更新
      【解决方案4】:
      db.<collection_name>.update({"_id":"5sq8uye1236g"},{
                              "name":"sam",
                              "age":20,
                              "token":12345,
                              "_id":""5sq8uye1236g'
                                  },{ upsert:true})
      
      db.<collection_name>.update({"_id":"5sq8uye1236g"},{ $set :{"token":12345}})
      

      【讨论】:

        猜你喜欢
        • 2011-04-27
        • 2014-09-25
        • 1970-01-01
        • 2021-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-10
        相关资源
        最近更新 更多