Code:
const items = await this.Products.find({
'_id': {
$in: [
...ids.map(id => new mongoose.Types.ObjectId(id.id))
]
}
}, {orders: 0}).exec()
The array ids
, can have duplicate ids. And it just returns that item once. I want it such that, it returns the item even if the same id is repeated multiple times.
If an example is, Ids are 1,2,1. Then it should return objects of ids, 1, 2 then again 1.
I couldn't find anything to try. If it can be done using javascript, feel free to drop your answer.
Thank you for trying to help me!
I tried to use $or operator, so that it searches for a single id. it didn't work.
As far as I'm aware it can't be done using a single find
or aggregate
query. In MongoDB The Definitive Guide (2020) it states:
The Aggregation Pipeline: If you’re familiar with pipelines in a Linux shell, such as bash, this is a very similar idea. Each stage has a specific job that it does. It expects a specific form of document and produces a specific output, which is itself a stream of documents. At the end of the pipeline we get access to the output, in much the same way that we would by executing a find query. That is, we get a stream of documents back. An individual stage of an aggregation pipeline is a data processing unit. It takes in a stream of input documents one at a time, processes each document one at a time, and produces an output stream of documents one at a time.
This shows that each document is passed to the $in
criteria one at a time, not the other way around. Once the document has matched the criteria it won't be passed again.