问题
I wonder know how to return the specified embedded keys ?
by the similar query
db.collection.find({"table_name": "change_in_real_gdp", {"data.*.actual":1, "data.*. upper_end_of_range"}})
Original document
{
"_id": "2012-06-20_change_in_real_gdp",
"table_name": "change_in_real_gdp",
"data": {
"2007": {
"actual": "4.8",
"upper_end_of_range": "-",
"upper_end_of_central_tendency": "-",
"lower_end_of_central_tendency": "-",
"lower_end_of_range": "-"
},
"2008": {
"actual": "6.9",
"upper_end_of_range": "-",
"upper_end_of_central_tendency": "-",
"lower_end_of_central_tendency": "-",
"lower_end_of_range": "-"
}
}
}
Expected result
{
"_id": "2012-06-20_change_in_real_gdp",
"table_name": "change_in_real_gdp",
"data": {
"2007": {
"actual": "4.8",
"upper_end_of_range": "-",
},
"2008": {
"actual": "6.9",
"upper_end_of_range": "-",
}
}
}
回答1:
You cannot use regex in projection. You need to explicitly specify the projection
argument to the .find() method
db.collection.find({},
{
"data.2007.actual": 1,
"data.2007.upper_end_of_range": 1,
"data.2008.actual": 1,
"data.2008.upper_end_of_range": 1,
"table_name": 1
}
)
回答2:
it can be achieve using query manipulation
so i have attached some code to achieve this
var projection = '{';
var start_year = 2007;
var end_year = 2008;
for(var counter=start_year;counter<=end_year;counter++) {
var attr1 = "\"data."+counter+".actual\"";
var attr2 = "\"data."+counter+".upper_end_of_range\"";
projection += attr1+':1,'+attr2+':1';
if(counter !== end_year)
projection += ',';
else
projection += '}';
}
var obj = JSON.parse(projection);
db.people.find({"table_name": "change_in_real_gdp"},obj);
Thanks
来源:https://stackoverflow.com/questions/29250081/how-to-projection-filter-embedded-keys-with-applying-regex-on-key