MongoDB在一个对象数组中,只显示具有指定值的对象



我拥有的MongoDB架构:

const userTaskSchema = new mongoose.Schema(
{
{...}{..}{...}{..} //Multiple objs above here, I just need help with this userTasks
userTasks: [
// Array of tasks with date
{
task: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
done: {
type: Boolean,
default: false,
},
},
],
},

任务数组如下:当前输出

"userTasks": [
{
"done": true,
"_id": "6059c57339d5590b04cb0fec",
"task": "abc",
"date": "2021-03-23T10:39:47.881Z"
},
{
"done": false,
"_id": "6059c57739d5590b04cb0fed",
"task": "abc",
"date": "2021-03-23T10:39:51.558Z"
},
{
"done": false,
"_id": "6059c57839d5590b04cb0fee",
"task": "abc",
"date": "2021-03-23T10:39:52.528Z"
},
{
"done": false,
"_id": "6059c57939d5590b04cb0fef",
"task": "abc",
"date": "2021-03-23T10:39:53.497Z"
},
{
"done": true,
"_id": "6059c57a39d5590b04cb0ff0",
"task": "abc",
"date": "2021-03-23T10:39:54.323Z"
}
],

我想要的输出是只存在done : false值的数组,我不想要任何done : true

我无法更改模式,这是我必须使用的。

我想要的输出:

"userTasks": [
{
"done": false,
"_id": "6059c57739d5590b04cb0fed",
"task": "abc",
"date": "2021-03-23T10:39:51.558Z"
},
{
"done": false,
"_id": "6059c57839d5590b04cb0fee",
"task": "abc",
"date": "2021-03-23T10:39:52.528Z"
},
{
"done": false,
"_id": "6059c57939d5590b04cb0fef",
"task": "abc",
"date": "2021-03-23T10:39:53.497Z"
},
],

我找不到任何查询来获得所需的结果。请帮忙。

演示-https://mongoplayground.net/p/GBF1aWVu0k7

在聚合查询中使用$filter

$project

db.collection.aggregate({
"$project": {
a: 1,
"userTasks": {
$filter: {
input: "$userTasks",
as: "task",
cond: { "$eq": [ "$$task.done", true] //this is working for me
}
}
}
}
})

最新更新