我有一个具有以下架构的集合,
{
"_id" : ObjectId("58b9d6b9e02fd02963b7d227"),
"id" : 1,
"ref" : [
{
"no" : 101
},
{
"no" : 100
}
]
}
当我尝试将子对象推入Object的ArrayList时,将其添加到array的末尾,但是我的目标是将对象推入数组的开始索引,我尝试使用此代码,但是将对象插入到array的末尾失败,
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应该是
{
"_id" : ObjectId("58b9d6b9e02fd02963b7d227"),
"id" : 1,
"ref" : [
{
"no" : 102
},
{
"no" : 101
},
{
"no" : 100
}
]
}
最佳答案
使用$ position修饰符指定数组中的位置。
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);