I am new to scala and I am trying to create a custom BsonDocument. As far as I read in the documentation here, there's this method append(String key, BsonValue value)
that calls the put
method internally and I am trying to use it.
The problem is that when I append more than two fields, only the last two get appended. For example if I have a code like this:
var doc = new BsonDocument();
val mapAccounts = user.accounts.map(e => new BsonString(e))
doc.append("$set", new BsonDocument("userName", new BsonString(user.userName)))
.append("$set", new BsonDocument("color", new BsonString(user.color)))
.append("$addToSet", new BsonDocument("accounts", new BsonDocument("$each", new BsonArray(mapAccounts.toList.asJava))))
println(s"The Bson user is $doc")
In this case, I get an output like:
The Bson user is { "$set" : { "color" : "teal" }, "$addToSet" : { "accounts" : { "$each" : ["1"] } } }
As you can see, the userName is not being appended. And it repeats for the last two appended elements if I change the order.
I already tried to use put
directly but still got the same result. Also tried to append individually like doc = doc.append(...)
and still the same.
What am I missing here?
You cannot have two $set
(a BSONDocument is basically a key-value mapping, and appending the same key again just resets it, in the same way a Map.put
would).
What you want is
"$set" : {
"color" : "teal",
"username": "Jim"
}