使用js代码时,我可以一一使用函数表达式;例如:array.map(***).filter(...)我可以在像猫鼬一样的地图之后使用过滤器吗?我的问题是这样的。我有一个如下的数据集:{"_id" : ObjectId("5e3bd328f3dec754e1b8e17d"),"userId" : "5e33ee0b4a3895a6d246f3ee","userName" : "jackiewillen","hasReviewedTimes" : 4,"notes" : [ { "time" : ISODate("2020-02-23T10:12:19.190Z"), "memoryLine" : [ { "hasReviewed" : false, "_id" : ObjectId("5e51df83966daeae41e7f5b1"), "memoryTime" : ISODate("2020-02-23T10:42:19.190Z") }, { "hasReviewed" : false, "_id" : ObjectId("5e51df83966daeae41e7f5b0"), "memoryTime" : ISODate("2020-02-23T22:12:19.190Z") } ] }, { "time" : ISODate("2020-02-23T10:45:26.615Z"), "memoryLine" : [ { "hasReviewed" : false, "_id" : ObjectId("5e51e746966daeae41e7f5bd"), "memoryTime" : ISODate("2020-02-23T11:15:26.615Z") }, { "hasReviewed" : false, "_id" : ObjectId("5e51e746966daeae41e7f5bc"), "memoryTime" : ISODate("2020-02-23T22:45:26.615Z") } ] },}我使用$map来获取包含memoryTime的项目现在少于memoryLine的项目,如下所示:db.notes.aggregate([{ $match: { "$and": [ { userId: '5e33ee0b4a3895a6d246f3ee'} ] }}, { $project: { notes: { $map: { input: "$notes", in: { $mergeObjects: [ "$$this", { memoryLine: { $filter: { input: "$$this.memoryLine", as: "mLine", cond: { $lt: ["$$mLine.memoryTime", new Date()] } } } } ] }, }, } }}])我的结果如下:"notes": [ { "time": "2020-02-23T10:12:19.190Z", "memoryLine": [ { "hasReviewed": false, "_id": "5e51df83966daeae41e7f5b1", "memoryTime": "2020-02-23T10:42:19.190Z" } ] }, { // =====> this item is not needed because of containing empty memoryLine "time": "2020-02-23T10:45:26.615Z", "memoryLine": [] // =======> i dont want empty item }, ]但我想要这样的结果:"notes": [ { "time": "2020-02-23T10:12:19.190Z", "memoryLine": [ { "hasReviewed": false, "_id": "5e51df83966daeae41e7f5b1", "memoryTime": "2020-02-23T10:42:19.190Z" } ] } ]所以我在$ map之后使用$ filter来过滤包含空memoryLine的项目:db.notes.aggregate([{ $match: { "$and": [ { userId: '5e33ee0b4a3895a6d246f3ee'} ] }}, { $project: { notes: { $map: { input: "$notes", in: { $mergeObjects: [ "$$this", { memoryLine: { $filter: { input: "$$this.memoryLine", as: "mLine", cond: { $lt: ["$$mLine.memoryTime", new Date()] } } } } ], $filter: { input: "$$this", as: "note", cond: { $ne: ["$$note.memoryLine", []] } } }, }, } }}然后这出了错。 最佳答案 您需要运行另一个$filter作为单独的管道阶段(出于可读性)或当前的最外部阶段。我希望第一个:{ $addFields: { notes: { $filter: { input: "$notes", cond: { $ne: [ "$$this.memoryLine", [] ] } } } }}关于node.js - 如何在 Mongoose 的$ map之后立即使用$ filter,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60360747/ 10-09 17:43