admin管理员组

文章数量:1336293

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 es 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'}

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 es 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'}
Share asked Feb 2, 2017 at 2:41 Shumi GuptaShumi Gupta 1,5252 gold badges19 silver badges28 bronze badges 1
  • Probably a duplicate of How can I add a key/value pair to a JavaScript object?. – RobG Commented Feb 2, 2017 at 3:02
Add a ment  | 

1 Answer 1

Reset to default 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.

本文标签: nodejskey value pair in javascriptStack Overflow