简体   繁体   中英

mongoose - exclude embedded document from query based on condition

I am using mongoose. I have the following document in my database:

question: {
    "id": "60ab9bd0d40a362189e842ff",
    "deletedAt": null
        "answers": [
        {
            "id": "60ab9e4e58a72f4768c5f63b",
            "deletedAt": "2021-05-28T20:23:30.409Z",
        },
        {
            "id": "60ab9e4e58a72f4768c5f64c",
            "deletedAt": null,
        },
    }
}

I would like to get all questions where the deletedAt field is null, as well as all answers where deletedAt field is null. So the result of my query should be this:

question: {
    "id": "60ab9bd0d40a362189e842ff",
    "deletedAt": null
        "answers": [
         {
            "id": "60ab9e4e58a72f4768c5f64c",
            "deletedAt": null,
        },
    }
}

What I have tried:

Question.aggregate([
    { $match: { deletedAt: null }},
    { $project: {
        answers: { 
          $filter: {
            input: "$answers",
            as: "answer",
            cond: { "$$answer.deletedAt": null }
          }
        }
      }
    },
    { $sort: sort },
    { $limit: limit + 1 }
]}

I would be very thankful for any kind of help!

use $eq operator to match condition in $filter operator,

    { $project: {
        answers: { 
          $filter: {
            input: "$answers",
            as: "answer",
            cond: { 
              $eq: ["$$answer.deletedAt", null]
            }
          }
        }
      }
    },

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM