【问题标题】:Using multiple queries together in mongodb在 mongodb 中同时使用多个查询
【发布时间】:2020-07-20 04:03:23
【问题描述】:

大家好,我在 mongodb 中有一个查询,我必须同时使用许多查询,所以这是我在 db 中的文档

id:                 ObjectId("5e8c1933ed43d408774f7fb9")
storyTitle:         "no"
storyDescription:   "no"
categoryID:         "5e882ed701e2ba37407328f1"
userID:             "5e896bc2feeed13a5336c066"
dateAdded:          2020-04-07T06:09:55.662+00:00
thankedBy:          ["ratnabh2615@gmail.com"]
thanked:            1
reportedBy:         ["ratnabh2615@gmail.com"]
reported:           1

//这只是一个例子,我的收藏中有很多这样的文档

我正在从客户端的 post api 中接收我的 userID 和 categoryID 现在我想要的是我想在哪里找到文档

  1. 文档的categoryID等于我从客户端收到的'categoryID'

  2. 文档的用户 ID 不等于我也从客户端收到的“用户 ID”

  3. 然后最后按照'thankedBy'数组的大小降序排列这个集合的文档

注意 - 仅当用户单击前端的某个按钮时才会添加thankedBy 数组,因此某些文档可能没有此字段。

【问题讨论】:

  • 这听起来像是 findsort 的直接使用,你有什么问题?

标签: node.js mongodb


【解决方案1】:

这里你不能使用$size在这些文档中按数组的长度对文档进行排序

我们可以使用aggregate管道获取每个文档中每个数组的长度,然后使用该长度对文档进行排序

这是一个例子

// replace MyCollectionName with your one
MyCollectionName.aggregate([
    {
        $match: { // add you search object here
            // you have to convert req.body.categoryID and req.body.userID to type ObjectID instead of Strings so the aggregate pipeline can understand it
            categoryID: req.body.categoryID,
            userID: { $ne: req.body.userID } // any userID except the req.body.userID
        }
    },
    {
        $project: { 
            // do that projection to be able to use the $size operator as it's valid only in $project operation
            // add all the fields you want, if there is some extra field in the documents and you don't need it in the query result, just don't mention it here
            // If you need all the document fields, then you have to list all of them here
            // here I will get these 4 fields only for simplicity (_id, storyTitle, storyDescription, thankedBy)
            _id: 1,
            storyTitle: 1, 
            storyDescription: 1, 
            thankedBy: 1,
            thankedByArrayLength: { $size: "$thankedBy" } // calculating the array length using the $size operator and assign that length to a new property called 'thankedByArrayLength'
        }
    },
    {
        $sort: { thankedByArrayLength: -1 } // sort documents by this thankedByArrayLength, 1 for ascending order, -1 for descending order
    }
])

现在您将获得按thankedBy 数组长度排序的文档,按照您的定义升序或降序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 2019-03-31
    • 2021-12-30
    相关资源
    最近更新 更多