如何动态使用$ push in mongo query

时间:2017-05-25 20:46:57

标签: javascript mongodb meteor

我的文档格式如下:

{ 
"Students" : {
    "Week1" : {
        "Monday" : [

        ], 
        "Tuesday" : [

        ], 
        "Wednesday" : [

        ], 
        "Thursday" : [

        ], 
        "Friday" : [

        ], 
        "Saturday" : [

        ], 
        "Sunday" : [

        ]
    }, 
    "Week2" : {
        "Sunday" : [

        ], 
        "Monday" : [

        ], 
        "Tuesday" : [

        ], 
        "Wednesday" : [

        ], 
        "Thursday" : [

        ], 
        "Friday" : [

        ], 
        "Saturday" : [

        ]
    }, 
    "Week3" : {
        "Sunday" : [

        ], 
        "Monday" : [

        ], 
        "Tuesday" : [

        ], 
        "Wednesday" : [

        ], 
        "Thursday" : [

        ], 
        "Friday" : [

        ], 
        "Saturday" : [

        ]
    }, 
    "Week4" : {
        "Sunday" : [

        ], 
        "Monday" : [

        ], 
        "Tuesday" : [

        ], 
        "Wednesday" : [

        ], 
        "Thursday" : [

        ], 
        "Friday" : [

        ], 
        "Saturday" : [

        ]
    }, 
    "Week5" : {
        "Sunday" : [

        ], 
        "Monday" : [

        ], 
        "Tuesday" : [

        ], 
        "Wednesday" : [

        ], 
        "Thursday" : [

        ], 
        "Friday" : [

        ], 
        "Saturday" : [

        ]
    }
  }
}

我想使用Week1作为变量动态地将一些元素推入Students.Week1.Monday。所以我想像这样构建它:

var dbNames = ['Zoe', 'Billy', 'Joey'];
var week = Week1; // week is dynamic entry
var query1 = {};
query1['Students.' + week + '.Monday'] = '$in: ' + dbNames;
Programs.update({ _id: teacherid }, { $push: query1 });

我搞砸了。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:2)

您可以动态创建对象以解决问题

var query = {};
var week = "DYNAMIC_VAL"; // Replace this
var day = "Monday";  // Dynamic Day
var dbNames = ['Zoe', 'Billy', 'Joey'];
query['Students'] = {};
query['Students'][week] = {};

// query['Students'][week][day] = { '$in': dBNames } // As per your query.
// but it should not work,
// if you want to push all elements of dbNames then you can use $each instead of $in

query['Students'][week][day] = { '$each': dBNames };


//console.log(JSON.stringify(query, null, 2));

Programs.update({ _id: teacherid }, { $push: query }, callback);