Reputation: 35
I have a collection with following schema,
{
"_id" : ObjectId("58b9d6b9e02fd02963b7d227"),
"id" : 1,
"ref" : [
{
"no" : 101
},
{
"no" : 100
}
]
}
when i tried to push the child Object to ArrayList of Object ,it added into end of array , but my goal is push the object into start index of an array, I tried with this code but it insert the object into end of array failed,
Java code,
Document push = new Document().append("$push", new Document().append("ref", new Document().append("no", 102)));
collection.updateMany(new Document().append("id", 1), push);
ExpectedResult should be,
{
"_id" : ObjectId("58b9d6b9e02fd02963b7d227"),
"id" : 1,
"ref" : [
{
"no" : 102
},
{
"no" : 101
},
{
"no" : 100
}
]
}
Upvotes: 2
Views: 730
Reputation: 1459
Use $position modifier to specify the location in the array.
Mongodb-Java driver,
ArrayList<Document> docList = new ArrayList<Document>();
docList.add(new Document().append("no", 102));
Document push = new Document().append("$push", new Document().append("ref", new Document().append("$each", docList).append("$position", 0)));
collection.updateMany(new Document().append("id", 1), push);
Upvotes: 3