gpt4 book ai didi

node.js - 对象数组中的 MongoDB,仅显示具有指定值的对象

转载 作者:行者123 更新时间:2023-12-04 15:02:19 24 4
gpt4 key购买 nike

我拥有的 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
}
}
}
}
})

关于node.js - 对象数组中的 MongoDB,仅显示具有指定值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66764778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com