0

In MongoDB, How to get the same data while querying to MongoDB collection with input.

Example: Test is the collection.

{
  "LIST": [{
                          "Number": "1",
                          "Name": "ABC"
           },{
                          "NUMBER": "2",
                          "DESCRIPTION": "EFG"
           },{
                          "NUMBER": "3",
                          "DESCRIPTION": "XYZ"
           }]
}

Query : db.getCollection('Test').find({ "Number" : { "$in" : [ "1" , "2" , "3"]}})

after query to DB getting order is different what in query mentioned.

After query to Collection getting following response like 2,3,1

Excepted Response is : 1,2,3 order

Please let me know how to achieve this.

jv42
  • 8,521
  • 5
  • 40
  • 64
Yellappa
  • 403
  • 1
  • 5
  • 16
  • you can add a `sort` condition with `ascending` as:`db.getCollection('Test').find({ "Number" : { "$in" : [ "1" , "2" , "3"]}}).sort({"Number":1})`. Here `1` is for ascending and `-1` is for descending. Checkout more at [sort](https://docs.mongodb.com/manual/reference/method/cursor.sort/). – vikscool Jun 18 '19 at 07:28
  • Ok. but in case the input is 3 ,1, 2 then repsonse is 3,1,2. Excepting ,what is sending input and ouput also same order. – Yellappa Jun 18 '19 at 07:30
  • you would have to use `aggregation` for a custom sorting or you have to play around with the `cursor` to get the custom ordered data. – vikscool Jun 18 '19 at 07:45

0 Answers0