首页 > 解决方案 > MongoDB过滤和排序数组

问题描述

我想通过某个 _id 查找,然后过滤作者、主题、内容和日期,并进行排序({timestamp:-1})。

我的数据如下所示:

{
    "_id": "1",
    "message": [{
        "_id": {
            "$oid": "609cbe47a45b594af4bc6b5a"
        },
        "author": "Dr. Jameson",
        "subject": "Lab Results Uploaded",
        "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sceleri...",
        "timestamp": {
            "$date": "2021-05-13T05:51:03.793Z"
        },
        "lastDateRead": {
            "$date": "2021-05-13T05:51:03.793Z"
        }
    }, {
        "_id": {
            "$oid": "609cbe47a45b594af4bc6b5b"
        },
        "author": "Dr. Johnson",
        "subject": "Lab Results",
        "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sceleri...",
        "timestamp": {
            "$date": "2021-05-13T05:51:03.793Z"
        },
        "lastDateRead": {
            "$date": "2021-05-13T05:51:03.793Z"
        }
    }]
}

所以我需要检查 _id 顶层是否为 1,然后进入消息并根据变量过滤其余部分并将其余部分传回。

通过 id 正确找到的当前代码

async function findPatientById(client, id) {
    const result = await client.db("any").collection("any").findOne({ _id: id});
    if (result) {
        console.log(`Found in the collection with the id '${id}'`);
        console.log(result);
    } else {
        console.log(`None found with the id'${id}'`);
    }
}

因此,如果我将“Dr. Jameson”作为变量传递并且 id =1 它会给

{
    "_id": {
        "$oid": "609cbe47a45b594af4bc6b5a"
    },
    "author": "Dr. Jameson",
    "subject": "Lab Results Uploaded",
    "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sceleri...",
    "timestamp": {
        "$date": "2021-05-13T05:51:03.793Z"
    },
    "lastDateRead": {
        "$date": "2021-05-13T05:51:03.793Z"
    }
}

标签: reactjsmongodbmongodb-queryaggregation-framework

解决方案


在 MongoDB 中,你不能这样做.find(),你需要使用.aggregate()thru,你可以执行更复杂的读取。

试试这个:

db.collection.aggregate([
  { $match: { _id: "1" } }, //filter docs
  { $unwind: "$message" }, // unwind array
  { $match: { "message.author": "Dr. Jameson" }}, //Add more filters
  { $sort: { "message.timestamp": -1 } },
  { $group: { _id: "$_id", message: { $push: "$message" } } } // Re-group messages array
])

替代$unwind您可以使用$filter阶段来实现相同的结果。不要忘记使用正确的索引

参考: MongoDB-聚合文档

测试: MongoDB-游乐场


推荐阅读