1

Assuming we have the following documents in our collection:

{
  name: 'Product1',
  prices: [
    { shop: 'shop1', price: 1 },
    { shop: 'shop2', price: 2 }
  ]
},
{
  name: 'Product2',
  prices: [
    { shop: 'shop3', price: 5 },
    { shop: 'shop4', price: 3 }
  ]
}

I need to get the following results from these documents using mongodb:

{
  name: 'Product1',
  bestPrice: { shop: 'shop1', price: 1 }
},
{
  name: 'Product2',
  bestPrice: { shop: 'shop4', price: 3 }
}

In other words, I want to get documents with their lowest prices ordered by value of the price field. How could I do it using using mongodb aggregation framework?

2
  • Could you show what you have tried yet Commented Oct 5, 2018 at 7:54
  • Anthony, I never tried to create that query, because I don't have an idea what approach should be used to solve this problem. Reading official docs and searching in the internet won't give me answers. Commented Oct 5, 2018 at 7:59

1 Answer 1

1

You can try below aggregation

db.collection.aggregate([
  { "$project": {
    "name": 1,
    "bestPrice": {
      "$arrayElemAt": [
        "$prices",
        {
          "$indexOfArray": [
            "$prices.price",
            { "$min": "$prices.price" }
          ]
        }
      ]
    }
  }}
])
Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I needed, thank you! About indexes: as I understand, it's enough to have index for prices.price to get best efficiency from this query?
No you have gone wrong. Indexes only works with $match and $sort stage. You can read more about it here docs.mongodb.com/manual/indexes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.