2015-12-01 24 views
1

我已经在MongoDB中一个下列文件如何添加值在单场MongoDB中

{ 
"_id" : "1999", 
    "Email" : "[email protected]", 
    "FirstName" : "personFirstNmae", 
    "LastName" : "personLastName", 
    "UserStatus" : "INACTIVE", 

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

我想在这里实现这一目标

{ 
"_id" : "1999", 
    "Email" : "[email protected]", 
    "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) 

请指导我怎样才能achive我desried结果和我在做什么错

回答

0

您需要使用$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"))) 
相关问题