首页 > 解决方案 > 如何查询数组并从 MongoDB 中检索它

问题描述

更新:

我在数据库上有一个文件,如下所示:

在此处输入图像描述

我的问题如下:

如何从friendsArrayfrom 数据库中检索前 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

在这一点上的任何答案都会非常有帮助!谢谢你!

标签: mongodbmongodb-querypymongo

解决方案


首先使用聚合unwind

然后sort根据 group_id 的时间戳创建排序数组使用addfieldsfilter获取数组的前 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
          
        }
      }
    },
    
  }
])

推荐阅读