【发布时间】:2018-07-14 01:09:07
【问题描述】:
我有一份格式为:
{
"_id": "test",
"TestArr": [
[1, 2],
[2, 3],
[3, 4]
]
}
我想在“TestArr”数组中插入另一个数组,同时按每个子数组中的第二项排序。
我已经确认我可以这样做:
db.ArrayTest.update(
{ "_id" : "test" },
{
$push: {
"TestArr" : {
$each : [[6,3]],
$sort: 1
}
}
}
)
这会导致文档:
{
"_id" : "test",
"TestArr" : [
[1.0, 7.0],
[2.0, 3.0],
[3.0, 4.0],
[6.0, 3.0]
]
}
我真正想要的是:
{
"_id" : "test",
"TestArr" : [
[2.0, 3.0],
[6.0, 3.0]
[3.0, 4.0],
[1.0, 7.0]
]
}
$sort : 1 在该更新中似乎正在对整个子数组进行排序。我知道在对文档数组进行排序时,我可以使用 $sort : { field: 1 } 指定特定的子字段进行排序。不确定如何使用子数组的特定项索引指定排序。
感谢任何帮助。
【问题讨论】:
-
您可以在特定索引上使用
$position修饰符来$push -
您好!您可以先进行更新,然后分别对结果数组进行排序……就像在两个不同的查询中一样?
标签: mongodb mongodb-query