在mongoDB集合中查询,投影和排序文档的多个字段

时间:2019-06-13 06:26:23

标签: mongodb

我有一个简单的mongoDB集合,名为usersCollection,其常规结构如下:

[
  {
    "username" : "john",
    "sex" : "m",
    "email" : "john@gmail.com",
    "courses" : [
        {
           "title" : "medicine",
           "grade": 25,
        },
        {
           "title" : "art",
           "grade": 29,
        },
        {
           "title" : "history",
           "grade": 21,
        }
    ]
  },
  {
    "username" : "jane",
    "sex" : "f",
    "email" : "jane@gmail.com",
    "courses" : [
        {
           "title" : "math",
           "grade": 20,
        },
        {
           "title" : "medicine",
           "grade": 30,
        }
    ]
  },
  {
    "username" : "sarah",
    "sex" : "f",
    "email" : "sarah@gmail.com",
    "courses" : [ ]
  },
  {
    "username" : "josh",
    "sex" : "f",
    "email" : "josh@gmail.com",
    "courses" : [
        {
           "title" : "english",
           "grade": 28,
        }
    ]
  },
  {
    "username" : "mark",
    "sex" : "m",
    "email" : "mark@gmail.com",
    "courses" : [
        {
           "title" : "history",
           "grade": 30,
        },
        {
           "title" : "medicine",
           "grade": 19,
        },
        {
           "title" : "math",
           "grade": 22,
        }
    ]
  }
]

每个用户都是usersCollection的成员,并且具有一些常规信息以及他/她已经完成的相对等级的课程列表。

谁能告诉我如何查询usersCollection以获得包含所有已完成特定课程的用户的对象的降序排序数组?此数组的每个对象都应包含相对用户的“名称”,“电子邮件”和“等级”。

例如,围绕课程名称为“ medicine”的usersCollection发起查询,我将获得以下数组:

[
  { 
    "username": "jane",
    "email": "jane@gmail.com", 
    "grade": 30
  },
  { 
    "username": "john",
    "email": "john@gmail.com", 
    "grade": 25
  },
  { 
    "username": "mark",
    "email": "mark@gmail.com", 
    "grade": 19
  }
]    

1 个答案:

答案 0 :(得分:2)

您可以使用mongoDB的排序和组管道进行管理。 如果您想获得任何特定的课程,可以在排序管道之前应用匹配管道。

db.users.aggregate([
    {
        $unwind: "$courses"
    },
    {
        $match: {
                'courses.title': 'medicine'
        }
    },
    {
        $sort: {
            'courses.title': -1,
            'courses.grade': -1,
        }
    },
    {
        $group: {
            _id: "$courses.title",
            records: {
                $push: {
                    "_id" : "$_id",
                    "username" : "$username",
                    "sex" : "$sex",
                    "email" : "$email",
                    "grade":"$courses.grade"
                }
            }
        }
    }
])