我在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)
请指导我如何实现我的悲惨结果以及我做错了什么
答案 0 :(得分: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")))