0

I have next article structure:

var articleSchema=new Schema({
    id : Number,
    title : String,
    sefriendly : String,
    created : Date,
    categories: [
        {
            id: Number,
            name: String,
            sefriendly: String,
            image: String
        }
    ],
    author: {
        id: Number,
        name: String
    }
});

So what I want is to take one latest article sorted by created field for a set of categoryIds. For example I have categories like Cinema, TV, Music, Books, and I want to take latest article for each category. Is it possible to do in one query?

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Eriendel
  • 911
  • 1
  • 9
  • 23

1 Answers1

1

First create index for created date and category ids:

db.article.ensureIndex({"created":-1,"categories.id":1})

then take latest article :

db.article.aggregate(    [  {$unwind : "$categories"}     { $sort: {"created":-1,"categories.id":1 } },      {        $group:          {            _id: {"categories_id":"$categories.id"},            lastDate: { $last: "$created" }          }      }  ] ,{"allowDiskUse":true})

Maybe there is little syntax error

Fariz Aghayev
  • 649
  • 5
  • 17