Joe Balin
Joe Balin

Reputation: 177

Excluding data in mongo aggregation

I'm working with a mongodb query. Each document in the collection looks like this:

{
  "_id": "12345",
  "name": "Trinity Force",
  "price": 3702,
  "comp": [
    "Zeal",
    "Phage",
    "Sheen",
  ]
}

I was working on a query that returns the 5 cheapest items (lowest price), with prices equal to 0 excluded (those trinkets though). I wrote this (sorry for poor formatting)

db.league.aggregate(  { $project : { _id : 1, name: 1, price: 1, comp: 0 } }, 
{ $match : {price : { $gt : 0 } } }, 
{ $sort: { price : 1 } }).limit(5)

I ran into two problems, though; the limit function doesn't seem to work with this aggregation, and neither does the $project. The output I'm looking for should exclude the item components (hence comp: 0) and limit it to 5 outputs. Could I get some assistance, please?

Upvotes: 0

Views: 165

Answers (2)

Gabe Rainbow
Gabe Rainbow

Reputation: 3738

imo, this is not aggregating but sorting results.

db.league.find({ price: { $gt :0} }, {comp: 0}).sort({price: 1}).limit(5)

nevertheless, i would test both for performance

Upvotes: 0

Skyprenet
Skyprenet

Reputation: 60

db.league.aggregate(
{ $project : { _id : "$_id", name: "$name", price: "$price"} },
{ $match : { "price" : { $gt : 0 } } },
{ $sort: { "price" : 1 } },
{ $limit : 5 })

This is aggregation query to return the 5 cheapest items

Upvotes: 3

Related Questions