mongodb - 如何查询数组并从 MongoDB 中检索它
问题描述
更新:
我在数据库上有一个文件,如下所示:
我的问题如下:
如何从friendsArray
from 数据库中检索前 10 个元素并根据值降序或升序对其进行排序lastTimestamp
。
我不想将所有值下载到我的 API,然后在 Python 中对它们进行排序,因为那会浪费我的资源。
我已经尝试使用此代码(Python):
listOfUsers = db.user_relations.find_one({'userId': '123'}, {'friendsArray' : {'$orderBy': {'lastTimestamp': 1}}}).limit(10)
但它只是给了我这个错误pymongo.errors.OperationFailure: Unknown expression $orderBy
在这一点上的任何答案都会非常有帮助!谢谢你!
解决方案
首先使用聚合unwind
然后sort
根据
group
_id 的时间戳创建排序数组使用addfields
并filter
获取数组的前 10 项
db.collection.aggregate([
{ $match:{userId:"123"}},
{
"$unwind": "$friendsArray"
},
{
$sort: {
"friendsArray.lastTimeStamp": 1
}
},
{
$group: {
_id: "$_id",
friendsArray: {
$push: "$friendsArray"
}
},
},
{
$addFields: {
friendsArray: {
$filter: {
input: "$friendsArray",
as: "z",
cond: {
$lt: [
{
$indexOfArray: [
"$friendsArray",
"$$z"
]
},
10
]
}// 10 is n first item
}
}
},
}
])
https://mongoplayground.net/p/2Usk5sRY2L2
和分页使用这个
db.collection.aggregate([
{ $match:{userId:"123"}},
{
"$unwind": "$friendsArray"
},
{
$sort: {
"friendsArray.lastTimeStamp": 1
}
},
{
$group: {
_id: "$_id",
friendsArray: {
$push: "$friendsArray"
}
},
},
{
$addFields: {
friendsArray: {
$filter: {
input: "$friendsArray",
as: "z",
cond: {
$and: [
{
$gt: [
{
$indexOfArray: [
"$friendsArray",
"$$z"
]
},
10
]
},
{
$lt: [
{
$indexOfArray: [
"$friendsArray",
"$$z"
]
},
20
]
},
]
}// 10 is n first item
}
}
},
}
])
推荐阅读
- javascript - TypeError: 无法删除 # 的属性 'Symbol(@xml.js.parent)'
- javascript - 在父 div 中滚动子 div
- android - 启用缩小时 Gradle 构建失败
- reactjs - 更新状态时出错(跳过状态的构造函数)
- c - 从程序集 x86 32 位调用 c 函数时未定义的引用
- android - 带有 Proguard 的 Android Swagger 客户端
- selenium - 无法使用硒右键单击新选项卡中的选项打开链接
- apache - serer迁移后未加载apache2默认主页
- reactjs - 是否需要显式导入组件?
- selenium - 如何找到具有整个文本为动态的元素的xpath