【问题标题】:MongoDB query on object name substringMongoDB 查询对象名称子字符串
【发布时间】:2018-09-08 07:27:39
【问题描述】:

我已将以下 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);

【问题讨论】:

标签: javascript mongodb


【解决方案1】:

这应该可以帮助您从 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,但它根本不可用。

【讨论】:

  • 您好,非常感谢!它完美地工作。有没有办法只返回价目表?现在我必须做result[0].gcp_price_list_as_array 来获得第一个对象,但我更愿意做gcp_price_list_as_array[0] 这可能吗?再次感谢。
  • 我不确定我是否理解... 聚合查询返回一个 列表 匹配文档。因此,您将不得不迭代该列表或访问特定项目,如结果 [0]。您能否重新表述您的问题?
  • 没关系,我自己找到了解决方案。不过,我还有一个问题。我可以将 VMIMAGE 存储在某种变量中吗?这样我就可以说 /variablename/ 了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 1970-01-01
  • 2020-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多