Home > Blockchain >  MongoDB - How to get an exact query data using $all
MongoDB - How to get an exact query data using $all

Time:10-25

I try to query data from MongoDB using this line of code:

forms = await AllForm.find({
         answers: {
           $all: [{ $elemMatch: { dateCreate: "2022-10-25" } }],
         },

It was supposed to return dates that are only "2022-10-25", but it turns out that it selected all the dates with the result below:

"status": true,
"message": "LIST_FORM",
"forms": [
    {
        "_id": "635711356b220b918529c29a",
        "formId": "635711356b220b918529c298",
        "title": "Quality",
        "department": "Quality",
        "answers": [
            {
                "username": "[email protected]",
                "dateCreate": "2022-10-25",
                "Keterangan": "[email protected]",
                "Jam_Kerja": "14:09"
            },
            {
                "username": "[email protected]",
                "dateCreate": "2022-10-24",
                "Keterangan": "[email protected]",
                "Jam_Kerja": "10:50"
            }
        ],
        "createdAt": "2022-10-24T22:27:01.673Z",
        "updatedAt": "2022-10-24T22:32:27.683Z",
        "__v": 0
    },
    {
        "_id": "63571d2285d6fb180cfa9f84",
        "formId": "63571d2285d6fb180cfa9f82",
        "title": "Quality_2",
        "department": null,
        "answers": [
            {
                "username": "[email protected]",
                "dateCreate": "2022-10-25",
                "Test": "[email protected]",
                "Date": "2022-10-12T00:00:00.000Z"
            },
            {
                "username": "[email protected]",
                "dateCreate": "2022-10-25",
                "Test": "[email protected]",
                "Date": "2022-10-12T00:00:00.000Z"
            }
        ],
        "createdAt": "2022-10-24T23:17:54.995Z",
        "updatedAt": "2022-10-24T23:19:29.981Z",
        "__v": 0
    }
]

Can someone please tell me where did I do wrong with the query?

CodePudding user response:

Think that the .find() query unable to complete such a complex projection.

You may look for aggregation query.

  1. $match - With dot notation, find the document(s with forms array contain the document with dateCreate is "2022-10-25" in nested answers array.

  2. $set - Set the answers array.

    2.1. $filter - Filter the matched document in the answers array.

forms = await AllForm.aggregate([
  {
    $match: {
      "answers.dateCreate": "2022-10-25"
    }
  },
  {
    $set: {
      answers: {
        $filter: {
          input: "$answers",
          cond: {
            $eq: [
              "$$this.dateCreate",
              "2022-10-25"
            ]
          }
        }
      }
    }
  }
])

Demo @ Mongo Playground

  • Related