mongodb - Mongo query for field name -


i have collection summarizes data related documents in other collections. it's structure like:

{     campaignid : objectid(...)     impressions : {         ...         '2016-09-20': 1800,         '2016-09-21': 1500,         '2016-09-22': 2000     },     clicks : {         ...         '2016-09-20': 60,         '2016-09-21': 55,         '2016-09-22': 80     } } 

i realize there better ways of doing it, it's can't control.

the issue need query documents had impressions in previous 7 days.

so need query based on field key instead of value.

is possible doing in query?

as need query based on field key instead of value first need provide keys previous n days(7 days in case). after building these keys(programmatically or manually ), can achieve in different ways -----

1 - using $where

db.collectionname.find({$where: function() {    var previous2days = ["2016-09-21","2016-09-20"]    (var field in this.impressions) {        if(previous2days.indexof(field) > -1) return true;    }   return false; }}) 

2. using $exists

db.getcollection('test').find({  "$or":     [      { "impressions.2016-09-21" : { "$exists": true } },      { "impressions.2016-09-20" : { "$exists": true } }      //add more conditional objects consider data more previous dates     ] }) 

to build kind of query programmatically (taking javascript example build query)

var previous2days = ["2016-09-21","2016-09-20"] var query = { "$or" : [] } for(var key in previous2days) {     var q = {}     q["impressions."+previous2days[key]] = { "$exists" : true }     query.$or.push(q) } console.log(json.stringify(query)) 

this give final query in required format

{"$or":[{"impressions.2016-09-21":{"$exists":true}},{"impressions.2016-09-20":{"$exists":true}}]} 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -