1

Lets say that I have an array on Object Ids:

[ 1, 2, 3, 4, 5 ]

and I have a collection called user which contains this value:

[
  {
     _id: 3,
     name: 'hehe'
  },

  {
     _id: 5,
     name: 'hehe1'
  },

  {
     _id: 2,
     name: 'hehe2'
  },

  {
     _id: 1,
     name: 'hehe3'
  },

  {
     _id: 4,
     name: 'hehe4'
  },

  {
     _id: 6,
     name: 'hehe5'
  }
]

How do i query the array object ids to the collection "user"? which the result should be the same order as the array of Object ids, would that be possible?

Thanks in advance!

frost kazuma
  • 350
  • 1
  • 8
  • 24
  • 2
    https://stackoverflow.com/questions/22797768/does-mongodbs-in-clause-guarantee-order – Ashh Jan 21 '20 at 04:56

2 Answers2

1

You can use $in to filter the documents and then you can use $indexOfArray to add special field which can be used as a key for $sort:

db.collection.aggregate([
    {
        $match: { _id: { $in: [ 1, 2, 3, 4, 5 ] } }
    },
    {
        $addFields: { idx: { $indexOfArray: [ [ 1, 2, 3, 4, 5 ], "$_id" ] } }
    },
    {
        $sort: { idx: 1 }
    }
])

Mongo Playground

mickl
  • 48,568
  • 9
  • 60
  • 89
0

To get the documents of Id array you can use $in as follows

collection.find( { key: { $in: [array] }}, callback );

NOTE:

Its not recommended to use order of documents to do some logic. We can't expect the order the same all time.

Subburaj
  • 5,114
  • 10
  • 44
  • 87