0

my guestMin and guestMax are both strings, and I want to add them together and put the sum into guestSum.

I tried this:

$project:{
    "_id" : 1,                                 
    "name" : 1,
    "guestsMin" : 1,
    "guestsMax" : 1,
    "guestSum" : parseInt("guestsMin") + parseInt("guestsMax"),
    "gmapsdata" : 1
}

this does not show the guestSum at all

$project:{
    "_id" : 1,                                 
    "name" : 1,
    "guestsMin" : 1,
    "guestsMax" : 1,
    "guestSum" : { $add: [ parseInt("guestsMin"), parseInt("guestsMax") ] },
    "gmapsdata" : 1
}

this gives "guestSum": null,

    "guestSum" : { $add: [ parseInt("$guestsMin"), parseInt("$guestsMax") ] },              

this gives "guestSum": null,

    "guestSum" : { $multiply: [ parseInt("$guestsMin"), parseInt("$guestsMax") ] },

this gives "guestSum": null,

    "guestSum" : { $multiply: [ parseInt("property.guestsMin"), parseInt("property.guestsMax") ] },

this gives "guestSum": null,

Im running out of ideas, anyone?

torbenrudgaard
  • 2,375
  • 7
  • 32
  • 53
  • 2
    seems like you cannot convert the string to the number in aggregation pipeline https://stackoverflow.com/questions/25983228/convert-a-string-to-a-number-in-mongodb-projection – Sergey Berezovskiy Jul 05 '17 at 12:43
  • @Sergey hmmm perhaps you are right - but when I remove the parseInt, then it complains about multiplying strings. So it looks like the parseInt part is working fine. Just crap that I have to do a loop in js to add these two numbers together. – torbenrudgaard Jul 05 '17 at 13:11
  • 2
    The right thing to do here is fix all the docs so that these fields use numeric values. Otherwise you'll be fighting this forever. – JohnnyHK Jul 05 '17 at 13:40
  • @JohnnyHK hehe exactly!! So I did - last night I converted all the guestMin and guestMax to be numeric. And that made things a lot more easy – torbenrudgaard Jul 06 '17 at 06:41

1 Answers1

0

The solution was this:

"guestSort" : { $multiply: [ "$guestsMin", "$guestsMax"] },

"property.guestsMin" did not work

"guestsMin" did not work

"$property.guestsMin" did not work

but... "$guestsMin" worked

torbenrudgaard
  • 2,375
  • 7
  • 32
  • 53