Search code examples
javascriptmongodbmeteorkey-value

How to query a key:value pair in MongoDb via Javascript?


I've checked and even though I found similar questions mine is different as I'm using a variable key.

My data is as follows:

{
  "_id": "p9AXNCtfX5AWT5jRw",
  "chr": "1",
  "cousins": [
    "B1KLeIiQE",
    "H195r77hQ4",
    "rkFnSX7n74",
    "H8P6QcQXX"
  ],
  "end": {
    "B1KLeIiQE": 26384690,
    "H195r77hQ4": 25029488,
    "rkFnSX7n74": 26384690,
    "H8P6QcQXX": 25224010
  },
  "numCousins": 4,
  "start": {
    "B1KLeIiQE": 18683049,
    "H195r77hQ4": 18643577,
    "rkFnSX7n74": 18650794,
    "H8P6QcQXX": 18643577
  }
}

It's easy to access the 2 corresponding key:value objects start and end in JS via gDoc.start[kitUser] where kitUser will be any of the 4 strings present in the cousins array above.

So eg querying for the above document via the terminal would be:

db.groups.find({
  cousins: "B1KLeIiQE",
  chr: "1",
  "start.B1KLeIiQE": {
    $lte: 35000000
  },
  "end.B1KLeIiQE": {
    $gte: 1
  }
})

and I'd then convert the respective key 'B1KLeIiQE' to the value of 18683049 for start and 26384690 for end.

However I can't get the above query to work in Javascript as I can't resolve the field to query in a flexible way (meaning to include whichever value the key has to generate the 'start.B1KLeIiQE' and also 'end.B1KLeIiQE').

My current (failing) code looks like this):

const chr = '1';
const start = 1;
const end = 35000000;
const groupsArray = Groups.find({ chr, 'start.kitUser': { $lte: end }, 
'end.kitUser': { $gte: start }, cousins: kitUser }).fetch();

I also can't create an index on these 2 key:value objects (as there is a limit 1024 bytes per index and I have 1 document that goes has 1853 bytes) but I do have a compound index on cousins and chr which narrows the results before the filter is applied.

I do like the simple structure of the 2 key:value objects but I'm open for suggestions to change that format so that I can run the query in Javascript (Meteor).


Solution

  • You have syntax error in your code, try this:

    const chr     = '1';
    const start   = 1;
    const end     = 35000000;
    const kitUser = 'B1KLeIiQE';
    const query   = {};
    query['chr']  = chr;
    query['start.' + kitUser]  = { '$lte': end };
    query['end.' + kitUser]  = { '$gte: start }; 
    query['cousins']  = kitUser;
    const groupsArray = Groups.find(query).fetch();