2

Applying filters in MongoDb

I need to apply filters in mongoDb in an embedded document so how can I make a query like

Example:

var query = {
_id:userId,
'match.Id':matchId,
'match.userId':userId1
}

now I want to apply filters lets suppose

case 1: my query should be like

 var query = {
    _id:userId,
    'match.Id':matchId,

    }

case 2 :

 var query = {
    _id:userId,
    'match.userId':userId1
    }

there can be many cases like this

So my question is how can I make this query object in node.js/javascript

My work : I can create multiple key in an object but creating key as below doesn't works

var query={}
query._id:userId // works
query.'match.userId':matchId // error
query.match.userId:matchId //error

tried below code got desired output but it comes with square bracket but type of arr is object

var arr = [];
arr[ 'key3.abc' ] = "value3";
arr[ 'key2.abc' ] = "value3";
console.log(arr)//[ 'key3.abc': 'value3', 'key2.abc': 'value3' ]

desired output:

{'key3.abc': 'value3', 'key2.abc': 'value3'}
Shumi Gupta
  • 1,505
  • 2
  • 19
  • 28
  • Probably a duplicate of [*How can I add a key/value pair to a JavaScript object?*](http://stackoverflow.com/questions/1168807/how-can-i-add-a-key-value-pair-to-a-javascript-object). – RobG Feb 02 '17 at 03:02

1 Answers1

5

Change [] to {}

 var obj = {}; 
 obj[ 'key3.abc' ] = "value3";       
 obj[ 'key2.abc' ] = "value3"; 

 console.log(obj) // { 'key3.abc': 'value3', 'key2.abc': 'value3'}

N.B. We can assign or access a JavaScript object by square ([]) notation when key contains special character e.g. space, dot etc.

Sajib Khan
  • 22,878
  • 9
  • 63
  • 73
  • 2
    Square brackets are required for any property name that doesn't fit the criteria for a valid identifier. E.g. a property name can contain a digit but dot notation must be used if it starts with a digit. `foo.d2` is OK, `foo.2d` must be `foo['2d']`. – RobG Feb 02 '17 at 03:03