3

Here is an example of the document I'm working on:

{
            "_id" : ObjectId("5b35019563726438989381d3"),
            "ref" : "123",
            "nom" : "pc",
            "Revendeurs" : [
                    {
                            "revendeur" : "Tdiscount",
                            "selecteur_prix" : ".price",
                            "hist_prix" : [
                                    {
                                            "date" : ISODate("2018-06-28T00:00:00Z"),
                                            "prix" : 200
                                    },
                                    {
                                            "date" : ISODate("2018-06-27T00:00:00Z"),
                                            "prix" : 100.8}
                            ]
                    }
            ]
    }

I want to query the max of 'prix' field. I need also to list all the 'prix' by 'revendeur' but Mongodb is returning only empty result.

When executing this query :

db.Tunicompare.aggregate([
    { $unwind: '$Revendeurs' }, 
    { $group: { _id: null, max: { $max: '$Revendeurs.hist_prix.prix' } } },
    { $project: { max: 1, _id:0 } }
])

I get this result (instead of getting only 200 as a maximum)

{ "max" : [ 200, 100.8 ] }
Alex Blex
  • 34,704
  • 7
  • 48
  • 75
Amira Bedhiafi
  • 8,088
  • 6
  • 24
  • 60
  • https://docs.mongodb.com/manual/reference/operator/aggregation/max/index.html#array-operand – Alex Blex Jun 29 '18 at 11:50
  • When trying with this query :db.Tunicompare.aggregate([{$group: { _id: "$ref",maxPrice: { $max: "$Revendeurs.hist_prix.prix" } } }]) I have this result { "_id" : "123", "maxPrice" : [ [ 200, 100.8 ] ] } – Amira Bedhiafi Jun 29 '18 at 12:07
  • Please read the docs behind the link, it has exact answer - project max per document, then group max for all documents. – Alex Blex Jun 29 '18 at 12:21

2 Answers2

1

If you want to find the max value throughout both outer & inner lists, do something like this(Globally max value):

db.Tunicompare.aggregate([
    { $unwind: '$Revendeurs' }, 
    { $unwind: '$Revendeurs.hist_prix' },
    { $group: { _id: null, max: { $max: '$Revendeurs.hist_prix.prix' } } },
    { $project: { max: 1, _id:0 } }
])

Output

/* 1 */
{
    "max" : 200.0
}
Afridi
  • 6,753
  • 2
  • 18
  • 27
1

With $reduce. Give it a try MongoPlayground:

db.collection.aggregate([
  {
    $unwind: "$Revendeurs"
  },
  {
    $group: {
      _id: null,
      prixArr: {
        $push: "$Revendeurs.hist_prix.prix"
      }
    }
  },
  {
    $project: {
      "_id": 0,
      "max": {
        $reduce: {
          input: "$prixArr",
          initialValue: 0,
          in: {
            $max: "$$this"
          }
        }
      }
    }
  }
])

Output:

[
  {
    "max": 200
  }
]
Alexis Facques
  • 1,783
  • 11
  • 19