0

Let's say I have an Document like so.

const User = {
    info: {
        id: 123,
    },
    data: {
        111:{},
        123:{value: 5},
        234:{value: 10},
    }
}

And I want to preform and aggregation that can check if 'data.123.value' is greater than 10.

Is something like that possible with mongo? This is what I have so far, but it's not working.

aggregate([
{
    $project: {
    UserId: '$info.id',
    }
},
{
    $match: {
        'data[$UserId].value: {$gt: 10},
    }
}
]

I can do some server side work to preform this operation, but i would be really cool if mongo could just do this for me.

Any help is appreciated!

caden311
  • 972
  • 8
  • 22
  • Can You explain in detail what You want to achieve? Are You sure that this document example is correct one? What if You want just have users collection and `value: 10` and You want to get users that has value more than 10 ? – num8er May 14 '18 at 22:00
  • I dummied up the document a little bit to simplify things. But I want to return all documents in the collection where their 'data' at the index of the 'info.id' is greater than 10. – caden311 May 14 '18 at 22:02
  • data can have other user info ids, so I need to index it by the info id for the given User doc. – caden311 May 14 '18 at 22:02
  • I think You should have 2 collections and models: 1. User (users collection), 2. UserData (user_data) and after that You can it using 2 requests to db: 1. get users id fields, 2. get user_data that has that object value. No-SQL databases does not like relational things and for that case You've to think different to achieve Your goal – num8er May 14 '18 at 22:05
  • Presuming `var userId = '123'';` Then: ``{ "$match": { `data.${userId}.value`: 123 } }``. I see you used a "single" `\`` but you didn't get the rest of the interpolation correct. Also `$match` **first** always as this is not the same as `select * from d where this = "a"` and the "order" in an aggregation pipeline is important to performance. – Neil Lunn May 15 '18 at 01:47

1 Answers1

0
   aggregate([
      {$project:{dataToarray:{$objectToArray: "$data"} }},     
      {$unwind:"$dataToarray"},
      {$match:{v:{$gt:10}}}
   ])

using $objectToArray operator https://docs.mongodb.com/manual/reference/operator/aggregation/objectToArray/

new in operator in 3.6 version

Ahmed Kesha
  • 810
  • 5
  • 11
  • Not what the question was asking. They wanted to use a variable to decide which key to search. Also, forcing projection in order to match on a value is a very bad idea in real world terms. – Neil Lunn May 15 '18 at 01:50