1

I'd like to use the $max operator in an aggregate but an ID is needed if I use a group.

My documents have this kind of structure:

{
    "_id" : ObjectId("5633d6c3425d449c2ed498dd"),
    "stuff" : 123,
    "names" : [ 
        {
            "type" : "primary",
            "value" : "Foobar"
        }, 
        {
            "type" : "alternate",
            "value" : "Lorem Ipsum"
        }, 
        {
            "type" : "alternate",
            "value" : "Bar foo"
        }
    ]
}

I tried to use a $max without group

db.foobar.aggregate([
    { $unwind: "$names" },
    { $max: "$names.value" }
]);

But get "exception: Unrecognized pipeline stage name: '$max'"

And also tried:

db.foobar.aggregate([
    { $unwind: "$names" },
    {
        $group:
        {
            _id: "",
            maxName: { $max: "$names.value" }
        }
    }
]);

But get

{
    "_id" : "",
    "maxName" : "7つの紋章、7つの部族"
}

Which is weird because I have strings with latin alphabet really longer such as : "Middleton's New Geographical Game of a Tour through England and Wales"

Am I missing something? Do you have any idea how can I use this $max?

Alex
  • 2,927
  • 8
  • 37
  • 56
  • 1
    can you post an input document? – Sarath Nair Dec 03 '15 at 09:27
  • @SarathNair of course, I add it! – Alex Dec 03 '15 at 09:29
  • 2
    Your second aggregate query looks fine to me. You are trying to find max based on String value. What are you really expecting? – Sarath Nair Dec 03 '15 at 09:32
  • 1
    @SarathNair Oh may be it's because I don't understand the $max then... because I get the following result7つの紋章、7つの部族" but I have data with latin alphabet longer (i.e. more characters!) – Alex Dec 03 '15 at 09:36
  • Are there any docs with names.value : "7つの紋章、7つの部族"? – Sarath Nair Dec 03 '15 at 09:53
  • @SarathNair Yes there is. I think $max gets the max value in the alphabet that's why I've got Korean or Chinese results on my tests. – Alex Dec 03 '15 at 09:59
  • Yes that's true. If you print the char code of '7' you get 65303. That means your query and also mongoDB is right. $max in string works based on character code comparison. Hope you are clear about it – Sarath Nair Dec 03 '15 at 10:01
  • Ok I get it. Thanks for your answer, I close my question. – Alex Dec 03 '15 at 10:03
  • @Alex you can use mapReduce if what you want is compare by length. The reason you are getting this result can be found [here](http://stackoverflow.com/questions/3630645/how-to-compare-unicode-strings-in-javascript) – styvane Dec 03 '15 at 10:08
  • @Alex What output do you need? can u add it to your question please? I think you need count here. But it will be helpful if u provide sample output. – Vishwas Dec 03 '15 at 13:00

0 Answers0