简体   繁体   中英

MongoDB Aggregation Framework : Using dynamic javascript variables in Project “key” field

Pretty much a newbie to MongoDB aggregation framework. I'm wondering if there is a way to use a Dynamic Variable to do a project in the aggregate framework.

Eg. Here's my code, it's not to the javascript syntax, but if you get the point :

// My javascript variable
var my_variable = "salary";    

//  
db.article.aggregate(
{ $project : {
    title : 1 ,
    author : 1 ,
}});

Now, in the above code, i want to replace dynamically the projection of "author" to "salary". To something like this

    db.article.aggregate(
{ $project : {
    title : 1 ,
    "my_variable" : 1 ,
}});

Which in this case will dynamically project the Salary.

Your variable here isn't really dynamic since it cannot change during the aggregation pipeline. The aggregation framework does not evaluate JavaScript, so whatever values you provide must be derived from the pipeline that is provided or the documents being processed.

However, you can certainly build pipelines programmatically to achieve your outcome.

For example, using the mongo shell you could create a variable to represent some (or all) of your aggregation pipeline:

var myProjection = {
    title : 1,
    author: 1,
}

// Replace author with salary
delete myProjection.author
myProjection.salary = 1

// Projection will be: { "title" : 1, "salary" : 1 }
db.article.aggregate({ $project: myProjection})

In this case the myProjection variable is evaluated by the mongo shell before the aggregation query is sent to the MongoDB server.

If you have the field name assigned to a variable, I would create a projection object and assign the field name as the variable value. Your code would then becomes:

    // My javascript variable
    var my_variable = "salary";

    var projection = { title: 1, author: 1 };
    delete projection.author;
    projection[my_variable] = 1;

    db.article.aggregate({$project: projection});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM