在Mongodb数组中有没有办法插入一个新元素before/after一个特定的元素位置
In Mongodb array is there any way to insert a new element before/after a specific element position
假设我有一个像
这样的文件
{
"_id" : 5,
"rows": [
{ "id" : "aab", "value":100},
{ "id" : "aac", "value":400},
{ "id" : "abc", "value":200},
{ "id" : "xyz", "value":300},
]
}
我需要在 "rows" 数组中插入一个新的子文档
{ "id" : "qwe", "value":300}
元素位置前
{ "id" : "abc", "value":200}
我尝试使用以下命令将元素插入特定位置的命令
db.collection.update(
{
"_id" : 5,
"rows.id": "abc"
},
{
'$push': {
'rows': {
'$each': [{ "id" : "qwe", "value":300} ],
'$position': 2
}
}
}
)
正在运行。但问题在这里我必须指定
'$position': 2
这是一个静态值。
我的要求是在数组中的特定元素之前插入一个新元素。即位置可能是动态值。
有人可以帮忙吗?
事先进行一些 JavaScript 操作,您可以使用 map 函数获取需要插入新元素的特定数组对象元素的索引。首先,使用集合上的 findOne()
方法从文档中获取行数组:
var rows = db.collection.findOne({"_id": 5, "rows.id": "abc"}).rows,
pos = rows.map(function(e) { return e.id; }).indexOf("abc");
然后在更新语句中使用变量pos
:
db.collection.update(
{
"_id" : 5,
"rows.id": "abc"
},
{
"$push": {
"rows": {
"$each": [{ "id" : "qwe", "value":300} ],
"$position": pos
}
}
}
);
假设我有一个像
这样的文件{
"_id" : 5,
"rows": [
{ "id" : "aab", "value":100},
{ "id" : "aac", "value":400},
{ "id" : "abc", "value":200},
{ "id" : "xyz", "value":300},
]
}
我需要在 "rows" 数组中插入一个新的子文档
{ "id" : "qwe", "value":300}
元素位置前
{ "id" : "abc", "value":200}
我尝试使用以下命令将元素插入特定位置的命令
db.collection.update(
{
"_id" : 5,
"rows.id": "abc"
},
{
'$push': {
'rows': {
'$each': [{ "id" : "qwe", "value":300} ],
'$position': 2
}
}
}
)
正在运行。但问题在这里我必须指定
'$position': 2
这是一个静态值。
我的要求是在数组中的特定元素之前插入一个新元素。即位置可能是动态值。
有人可以帮忙吗?
事先进行一些 JavaScript 操作,您可以使用 map 函数获取需要插入新元素的特定数组对象元素的索引。首先,使用集合上的 findOne()
方法从文档中获取行数组:
var rows = db.collection.findOne({"_id": 5, "rows.id": "abc"}).rows,
pos = rows.map(function(e) { return e.id; }).indexOf("abc");
然后在更新语句中使用变量pos
:
db.collection.update(
{
"_id" : 5,
"rows.id": "abc"
},
{
"$push": {
"rows": {
"$each": [{ "id" : "qwe", "value":300} ],
"$position": pos
}
}
}
);