Search code examples
mongodbmeteor

Mongo db Collection find returns from the first entry not from last from client side


I am using mongodb and i am querying the database with some conditions which are working fine but the results are coming from the first entry to last where as i want to query from the last added entry to the collection in database

TaggedMessages.find({taggedList:{$elemMatch:{tagName:tagObj.tagValue}}}).fetch()

Solution

  • Meteor uses a custom wrapped version of Mongo.Collection and Mongo.Cursor in order to support reactivity out of the box. It also abstracts the Mongo query API to make it easier to work with.

    This is why the native way of accessing elements from the end is not working here.

    On the server

    In order to use $natural correctly with Meteor you can to use the hint property as option (see the last property in the documentation) on the server:

    const selector = {
      taggedList:{ $elemMatch:{ tagName:tagObj.tagValue } }
    }
    
    const options = {
      hint: { $natural : -1 }
    }
    
    TaggedMessages.find(selector, options).fetch()
    

    Sidenote: If you ever need to access the "native" Mongo driver, you need to use rawCollection

    On the client

    On the client you have no real access to the Mongo Driver but to a seemingly similar API (called the minimongo package). There you won't have $natural available (maybe in the future), so you need to use sort with a descenging order:

    const selector = {
      taggedList:{ $elemMatch:{ tagName:tagObj.tagValue } }
    }
    
    const options = {
      sort: { createdAt: -1 }
    }
    
    TaggedMessages.find(selector, options).fetch()