Melroy Fernandes
Melroy Fernandes

Reputation: 381

MongoDB $in operator

I have a table with following values

[
{
   id: 1,
   name: "abc"
},
{
   id: 2,
   name: "lmn"
},
{
   id: 3,
   name: "xyz"
}
]

I have a query with $in as

{
  id: {
    $in: [ 2, 3, 1 ]
  }
}

i want the output to come like so:

[
{
  id: 2,
  name: "lmn"
},
{
  id: 3,
  name: "xyz"
},
{
  id: 1,
  name: "abc"
}
]

But it does not come like that. Is there a way I could achieve this output?

Upvotes: 0

Views: 47

Answers (1)

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

You have to add a $sort stage, as $in does not preserve order.

There are quite a few questions on stackoverflow about this issue for example this question.

Upvotes: 1

Related Questions