reactjs - 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"
}
}
解决方案
在 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-游乐场
推荐阅读
- c++ - Windows 或其他系统动态/共享库如何链接到 VS 到 MinGW 不兼容?
- tensorflow - 无法加载动态库“libcublas.so.10”;dlerror:libcublas.so.10:无法打开共享对象文件:没有这样的文件或目录;
- rest - 使用 SQLAlchemy 的 Flask REST API 中的整数范围
- python - 使用 python emoji 包无法正确显示表情符号
- python - 使用请求 api 到我可以迭代的 json 文件中
- javascript - 异常“Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException”
- python - 如何将列名及其值拆分到不同的列而不是多合一(熊猫)
- java - 改造 2 使用不总是 XML 或 Json 的响应
- xamarin.forms - Xamarin.Forms - 显示所有项目而不滚动
- node.js - database.ts 中出现意外的令牌 const