0

I want to query entries where a nested object has at least a key in list.

let keys = ['one','two','three']


const entries = await db.collection("users").find({
        [`object1.key1.object2`]: $has a at least a key in keys
    })

Returns

{object:{key:{object2:{one:{}}}}
{object:{key:{object2:{one:{},two:{}}}
{object:{key:{object2:{three:{}}}

How can I do this?

user1506145
  • 5,176
  • 11
  • 46
  • 75
  • 1
    If you have a list then use `$exists` with an `$or`. i.e ``find({ $or: keys.map(k => ({ [`object1.key.object2.${k}`]: { "$exists": true } })) })`` – Neil Lunn Mar 30 '19 at 00:22
  • @NeilLunn Oh thanks, thats how to do it. I thought there was something similar to $elemMatch but for objects, and you could use it together with $in or something... I knew about $exist, I don't really think these two questions are duplicates.. – user1506145 Mar 30 '19 at 09:27
  • I think they are, as you are really only looking for "keys that exist". Therefore the hold. You cannot use `$in` because that can only apply to **one** field. In all honesty variable key names in nested objects is not a great design choice. Databases use "values" and not "keys", so usually want you really want is consistently named properties within an array anyway. And that's basically why there is no "`$elemMatch` for objects", because it's not good practice to model this way. You're probably thinking "keys" are faster to lookup, but this is a database so you actually **index the values**. – Neil Lunn Mar 30 '19 at 09:33
  • @NeilLunn Oh I see, yes exactly, I just thought for performance reasons... So it's better to have `list1: [{key:1, list2:[ {key: 12} ] }, ...]` and then do `list1: { $elemMath: { key: 1, list2: $elemMatch: { key: { $in:keys } } } }`? I'm started thinking that an object is no different than an array, just that an array is indexed with 0,1,2 and object is with keys... Sometimes I might send the datastructure to client side and then its easier to lookup `obj[key]` than doing `list.find(itm => itm.id === key)`. – user1506145 Mar 30 '19 at 12:27

0 Answers0