I am trying to update a array field in a embedded document in mongodb using Spring Data MongoDB.
The structure of document which I want to be updated/inserted in mongodb collection is as below.
There can be more documents like this based on each type of the department , say "Sales","Marketing" and so on.
{
"timestamp": "2014-09-26T04:00:00.000Z",
"department": "accounts",
"employee": [
{
"type": "regular",
"names": [
"Raj",
"Kumar",
"Shankar"
]
},
{
"type": "contract",
"names": [
"Penny",
"Sheldon",
"bob"
]
},
{
"type": "temp",
"names": [
"jerry",
"kramer",
"bubbleboy"
]
}
]
}
Basically, I have my update query as below,
db.getCollection('mytest').update(
{
"timestamp" : "2014-09-26T04:00:00.000Z",
"department" : "accounts",
"employee.type" : "regular"
},
{ $addToSet: { "employee.$.names" : "Jo" } },
{
upsert: true
}
)
I have added upsert: true because if there is no document matching the query I want to insert the document into the mytest collection.
When I execute the same from mongo shell , I am getting the below error.
The positional operator did not find the match needed from the query. Unexpanded update: employee.$.names
Even If this works, I am not sure if we have similar support for implementing the same in Spring Data mongodb.
Also, my other query is, if I want to add/update employees for multiple departments, say "accounts" as well as "sales", it appears that I have to execute the same query with different values as the number of department I want to update ( if not present insert) accordingly.
Is there a better and efficient option like bulk/batch where-in I can update/insert employees for multiple departments at the same time in a single mongo update query. Also, is there support in spring data mongodb/mongotemplate for the same.