0

I am very new to MongoDB and have just started learning and working with it. I have a question about a query. This is the query:

db.getCollection("user_plates").count(
    {
        "plates": {
            $elemMatch: {
                registerDate: {
                    $gt: new Date("2024-03-20T00:00:00.000Z"),
                    $lt: new Date("2024-03-21T00:00:00.000Z")
                }
            }
        }
    }
);

As you know, if the query find at least one element in the array that satisfies both condition, it returns all the elements of that document. Now, I need to have only the elements from the array of that document, that the field "registerDate" satisfies both conditions. I do not want to see other elements of the array of that document. How should I modify the above query to achieve this?

Thanks in advance

2
  • Please show some sample input data - and use a MongoDB version which is not outdated. Commented Dec 29, 2024 at 14:50
  • 1
    Potential duplicate on StackOverflow: stackoverflow.com/q/3985214/14732669 Commented Dec 29, 2024 at 19:17

1 Answer 1

2

Some people use operators $unwind, $match, $group for that. However, $filter works better, i.e. less code and better performance.

It's not fully clear what you like to count - the number of documents or the number of matched elements. In general it would be like this one:

db.getCollection("user_plates").aggregate([
  { $set: 
    { "plates": 
      { $filter: {
         input: "$plates",
         cond: { $and: [
           { $gt: ["$$this.registerDate", new Date("2024-03-20T00:00:00.000Z")] }, 
           { $lt: ["$$this.registerDate", new Date("2024-03-21T00:00:00.000Z")] }
         ]}
        }
      }
    } 
  }
])
2
  • Thanks. I need to see the document and for each document, only the element that match the condition. I run your query and received this error: Unrecognized pipeline stage name: '$set' Commented Dec 30, 2024 at 8:14
  • 1
    This is related to my first comment. Use a MongoDB version which is not outdated. Try $addFields which is the same as $set Commented Dec 30, 2024 at 9:16

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.