0

I need to retrieve let's say the documents at position 1,5 and 8 in a MongoDB database using Mongoose. Is it possible at all to get a document by its position in a collection? If so, could you show how to do that?

I need something like this:

var someDocs = MyModel.find({<collectionIndex>: [1, 5, 8]}, function(err, docs) {

    //do something with the three documents

})

I tried to do the following to see what indexes are used in collection but I get the 'getIndexes is not a function' error:

var indexes = MyModel.getIndexes();

Appreciate any help.

chridam
  • 100,957
  • 23
  • 236
  • 235
Octtavius
  • 563
  • 8
  • 29

2 Answers2

0

If by position 5 for example, you mean the literal 5th element in your collection, that isn't the best way to go. A Mongo collection is usually in the order in which you inserted the elements, but it may not always be. See the answer here and check the docs on natural order: https://stackoverflow.com/a/33018164/7531267.

In your case, you might have a unique id on each record that you can query by. Assuming the [1, 5, 8] you mentioned are the ids, something like this should do it:

var someDocs = MyModel.find({ $or: [{ id: 1 }, { id: 5 }, { id: 8 }]}}, function(err, cb) {
    //do something with the three documents
})

You can also read about $in to replace $or and clean up the query a bit.

Community
  • 1
  • 1
Justin Hellreich
  • 575
  • 5
  • 15
  • The thing is that I need to get 3 random documents from a collection using Mongoose. So, the way I wanted to do it is by generating 3 random numbers and get documents using those numbers as index in the collection. So, if my function generated the numbers 1, 5 and 8, I would like to use these numbers. I know there is a mongo function to get random docs, but need to do it in mongoose. – Octtavius Feb 10 '17 at 15:43
  • Ahh, very interesting problem. Possibly something like [this](http://stackoverflow.com/questions/14644545/random-document-from-a-collection-in-mongoose) may help. The gist being: `Model.findOne().skip(random)`, although you would need three queries to get three random records. – Justin Hellreich Feb 10 '17 at 15:52
0

Assume you have this document in users collections:

{
  _id: ObjectId('...'),
  name: 'wrq',
  friends: ['A', 'B', 'C']
}

Code below to search first and thrid friend of user 'wrq':

db.users.aggregate(
  [
    {
      $match: {
        name: 'wrq'
      }
    },
    {
      $project:{
        friend1: {
          $arrayElemAt: ["$friends", 0]
        },
        friend3: {
          $arrayElemAt: ["$friends", 2]
        }
      }
    }
  ]
)
王如锵
  • 941
  • 7
  • 17