【发布时间】:2021-06-29 17:18:29
【问题描述】:
我在这样的集合中有一个条目:
{
"_id" : ObjectId("60c6f7a5ef86bd1a5402e928"),
"cid" : 1,
"array1" : [
{ "type": "car", value: 20 },
{ "type": "bike", value: 50 },
{ "type": "bus", value: 5 },
{ "type": "cycle", value: 100 },
...... 9000 more entry something like this
],
"array2" : [
{ "type": "laptop", value: 200 },
{ "type": "desktop", value: 15 },
{ "type": "tablet", value: 55 },
{ "type": "mobile", value: 90 },
...... 9000 more entry something like this
]
}
现在我想为分页目的对数据进行排序和切片。
为此,我编写了适用于切片情况但不适用于排序情况的查询。 这是我的查询,适用于切片情况
let val = await SomeCollectionName.findOne(
{ cid: 1 },
{ _id: 1 , array1: { $slice: [0, 10] } } ---> its return the 10 data. Initially it return from 0 to 10, then next call $slice: [10, 10]
).exec();
if (val) {
//console.log('Got the value')
}
console.log(error)
这是我使用切片添加排序时的查询
let val = await SomeCollectionName.findOne(
{ cid: 1 },
{ _id: 1 , array1: { $sort: { value: -1 }, $slice: [0, 10] } }
).exec();
if (val) {
//console.log('Got the value')
}
console.log(error)
有没有人指导我哪里错了或建议我什么是获取数据的有效方法。
更新
我正在从上述问题中得到答案,并为两个数组寻找相同的实现。 一切都是一样的。之前我在处理 1 个数组,这次我必须处理两个数组。
只是想知道这些事情是如何发生的 我编写了聚合查询,但一个数组结果很好,但其他数组在整个数组中返回相同的数据。
根据使用排序和切片处理单个数组的建议,这是我的查询
db.collection.aggregate([
{
"$match": {
"cid": 1
}
},
{
$unwind: "$array1"
},
{
$unwind: "$array2"
},
{
"$sort": {
"array1.value": -1,
"array2.value": -1,
}
},
{
$skip: 0
},
{
$limit: 3
},
{
$group:{
"_id":"$_id",
"array1":{$push:"$array1"},
"array2":{$push:"$array2"}
}
}
])
【问题讨论】:
-
它不应该工作。没有 $sort projection operator
标签: mongodb sorting mongoose slice