MongoDB select subdocument with aggregation function

0

I have a mongo DB collection that looks something like this:

{
    {
        _id: objectId('aabbccddeeff'),
        objectName: 'MyFirstObject',
        objectLength: 0xDEADBEEF,
        objectSource: 'Source1',
        accessCounter: {
                          'firstLocationCode' : 283, 
                          'secondLocationCode' : 543,
                          'ThirdLocationCode' : 564,
                          'FourthLocationCode' : 12,
                       }
    }
    ...
}

Now, assuming that this is not the only record in the collection and that most/all of the documents contain the accessCounter subdocument/field how will I go with selecting the x first documents where I have the most access from a specific location.

A sample "query" will be something like:

"Select the first 10 documents From myCollection where the accessCounter.firstLocationCode are the highest"

So a sample result will be X documents where the accessCounter. will be the greatest is the database.

Thank your for taking the time to read my question.

mongodb
aggregation-framework
asked on Stack Overflow Oct 23, 2014 by 0xGiddi • edited Jun 23, 2017 by Neil Lunn

1 Answer

1

No need for an aggregation, that is a basic query:

db.collection.find().sort({"accessCounter.firstLocation":-1}).limit(10)

In order to speed this up, you should create a subdocument index on accessCounter first:

db.collection.ensureIndex({'accessCounter':-1})

assuming the you want to do the same query for all locations. In case you only want to query firstLocation, create the index on accessCounter.firstLocation.

You can speed this up further in case you only need the accessCounter value by making this a so called covered query, a query of which the values to return come from the index itself. For example, when you have the subdocument indexed and you query for the top secondLocations, you should be able to do a covered query with:

db.collection.find({},{_id:0,"accessCounter.secondLocation":1})
.sort("accessCounter.secondLocation":-1).limit(10)

which translates to "Get all documents ('{}'), don't return the _id field as you do by default ('_id:0'), get only the 'accessCounter.secondLocation' field ('accessCounter.secondLocation:1'). Sort the returned values in descending order and give me the first ten."

answered on Stack Overflow Oct 23, 2014 by Markus W Mahlberg

User contributions licensed under CC BY-SA 3.0