Peterdeka
Peterdeka

Reputation: 387

MongoDB $in not only one result in case of repeated elements

I need to get the users whose ids are contained in an array. For this i'm using the $in operator, however being this inside an aggregate operation, i'd like to get back a specific user all the time it's id is present in the array, not just one. For example:

The ids array is A=[a,b,c,b] and U(x) is user with id x
with users.find({_id:{$in:A}}) i get these users as result: U(a),U(b),U(c)
instead i'd like to get back the result: U(a),U(b),U(c),U(b)

so get the user back every time it's id appears.

I understand that $in is working as expected but does anyone have an idea on how can i achieve this?

Thanks

Upvotes: 1

Views: 607

Answers (1)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24017

This isn't possible using a MongoDB query.

MongoDB's query engine iterates over the documents in a collection (or over an index if there's a useful one) and returns to you any documents that match your query, in the order it finds them. Whether b appears once, twice, or a hundred times in your query makes no difference: the document with _id of b matches the query and is returned once, when MongoDB finds it.

You can do a post-processing step in your programming language to repeat documents as many times as you want.

Upvotes: 1

Related Questions