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!

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.