我已将以下JSON文件上传到mongoDB数据库: https://cloudpricingcalculator.appspot.com/static/data/pricelist.json
我已成功使用app.js中的以下行访问它:
db.googlepricelist.find({},
{"gcp_price_list":1}).pipe(JSONStream.stringify()).pipe(res);
我想查询对象gcp_price_list
中的所有对象,其中对象的名称包含子字符串" VMIMAGE"。
例如,波纹管对象:
"CP-COMPUTEENGINE-VMIMAGE-F1-MICRO"
"CP-COMPUTEENGINE-VMIMAGE-G1-SMALL"
我无法弄清楚如何定义能够执行此操作的查询。
到目前为止,我试过这个:
db.googlepricelist.find({$where: function() {
for (var key in this.gcp_price_list) {
if (key.indexOf("VMIMAGE")!=-1) {
return true;
}
return false;
}
},}).pipe(JSONStream.stringify()).pipe(res);
答案 0 :(得分:0)
这应该让你从v3.4.4起开始工作:
db.googlepricelist.aggregate({
$project: {
"gcp_price_list_as_array": { $objectToArray: "$gcp_price_list" }, // transform "gcp_price_list" into an array of key-value pairs
}
}, {
$unwind: "$gcp_price_list_as_array" // flatten array
}, {
$match: { "gcp_price_list_as_array.k": /VMIMVAGE/ } // like filter on the "k" (as in "key") field using regular expression
})
您通常会尝试使用$ filter来过滤数组,但是,使用正则表达式并不起作用。这是一个开放的JIRA ticket,但它还没有。