[英]Mongodb-java How to Insert new object into starting Index of an array Object
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, 当我尝试将子对象推入Object的ArrayList时,将其添加到array的末尾,但是我的目标是将对象推入数组的开始索引,我尝试使用此代码,但是将对象插入到array的末尾失败,
Java code, Java代码
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, ExpectedResult应该是
{
"_id" : ObjectId("58b9d6b9e02fd02963b7d227"),
"id" : 1,
"ref" : [
{
"no" : 102
},
{
"no" : 101
},
{
"no" : 100
}
]
}
Use $position modifier to specify the location in the array. 使用$ position修饰符指定数组中的位置。
Mongodb-Java driver, Mongodb-Java驱动程序,
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.