【问题标题】:how to add values in a single field in mongodb如何在mongodb的单个字段中添加值
【发布时间】:2015-12-01 14:53:38
【问题描述】:

我在 mongodb 中有以下文档

{
"_id" : "1999",
    "Email" : "mail@example.com",
    "FirstName" : "personFirstNmae",
    "LastName" : "personLastName",
    "UserStatus" : "INACTIVE",

    "FollowingItems" : [
        {
            "FollowingItemUuid" : "g12345",
            "FollowingItemUuidType" : "GALLERY"
        }
    ]
}

我想实现这个

{
"_id" : "1999",
    "Email" : "mail@example.com",
    "FirstName" : "personFirstNmae",
    "LastName" : "personLastName",
    "UserStatus" : "INACTIVE",

    "FollowingItems" : [
        {
            "FollowingItemUuid" : "g12345",
            "FollowingItemUuidType" : "GALLERY"
        },
        {
            "FollowingItemUuid" : "M121",
            "FollowingItemUuidType" : "MUSEUM"
        }


    ]
}

这是我的代码

val q=QueryBuilder.start("_id").is("1999")
var update=collection.update(q.get,new BasicDBObject("$set",new BasicDBObject("FollowingItems.$.FollowingItemUuid","M121").append("FollowingItems.$.FollowingItemUuidType","MUSEUM")))

但它会引发以下异常

com.mongodb.WriteConcernException: { "serverUsed" : "Localhost:27017" , "ok" : 1 , "n" : 0 , "updatedExisting" : false , "err" : "cannot use the part (FollowingItems of FollowingItems.FollowingItemUuid) to traverse the element ({FollowingItems: [ { FollowingItemUuid: \"g12345\", FollowingItemUuidType: \"GALLERY\" } ]})" , "code" : 16837}
    at com.mongodb.CommandResult.getWriteException(CommandResult.java:90)
    at com.mongodb.CommandResult.getException(CommandResult.java:79)
    at com.mongodb.DBCollectionImpl.translateBulkWriteException(DBCollectionImpl.java:316)
    at com.mongodb.DBCollectionImpl.update(DBCollectionImpl.java:274)
    at com.mongodb.casbah.MongoCollectionBase$class.update(MongoCollection.scala:882)
    at com.mongodb.casbah.MongoCollection.update(MongoCollection.scala:1162)

请指导我如何实现我的预期结果以及我做错了什么

【问题讨论】:

    标签: java mongodb scala scala-2.11


    【解决方案1】:

    您需要使用$push 运算符来使用它。这是 MongoDB shell 命令:

      db.data.update({
      "_id": "1999"
     }, {
      "$push": {
        "FollowingItems": {
          "FollowingItemUuid": "M121",
          "FollowingItemUuidType": "MUSEUM"
        }
      }
    })
    

    这是等效的 QueryBuilder 语法:

    val q=QueryBuilder.start("_id").is("1999")
    var update=collection.update(q.get,new BasicDBObject("$push",new BasicDBObject("FollowingItems.$.FollowingItemUuid","M121").append("FollowingItems.$.FollowingItemUuidType","MUSEUM")))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-19
      • 2013-12-01
      • 2015-02-26
      • 1970-01-01
      • 2012-07-01
      • 2020-06-19
      相关资源
      最近更新 更多