Domanda

I'm using Casbah Scala driver to do CRUD operations on the MongoDB database. I would like to update a certain fields in a particular document. I'm using the findAndModify method, but to my surprise, the entire document is rewritten. My original document has 5 fields before findAndModify call in which I want to update 1 of its field. After the findAndModify call, I'm left with only 2 fields. Here is what I'm trying!

val mongoClient = MongoClient()
val db = mongoClient(MongoDBSetup.TEMP_DATABASE)
val query = MongoDBObject("uid" -> userExam.uid)
val update = MongoDBObject("answers" -> userExam.userAnswers)
db(MongoDBSetup.MONGO_DB_COLLECTION_USER_EXAM).findAndModify(query, update)

Is there anything else that I should consider so that only the answers field is modified in the document?

È stato utile?

Soluzione

You need to do it with a $set update document to modify only a subset of the fields. This should do what you want:

val update = MongoDBObject(
  "$set" -> MongoDBObject("answers" -> userExam.userAnswers)
)

More about $set in mongodb: http://docs.mongodb.org/manual/reference/operator/update/set/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top