【问题标题】:NodeJS storing mongo aggregate query in DB or property fileNodeJS 在数据库或属性文件中存储 mongo 聚合查询
【发布时间】:2020-07-22 13:05:31
【问题描述】:

我的 nodejs api 中有以下 mongo 聚合查询。它工作得很好。

queryRes = await Seller.aggregate([
  {$match: {}},{$addFields : {"communication_information":{$filter:{ input: "$communication_information",as: "communication_information",
       cond: {"$or" :[{$eq: ["$$communication_information.communication_information_type",  "phone"  ] },
                {$eq: ["$$communication_information.communication_information_type", "email"] },
                ]}}}}},{ "$project": {"_id": 1,"initial_name": 1,"first_name": 1,"last_name": 1,"gender":1,"communication_information":1, }},
                { $sort : { first_name : 1, last_name: 1 } },])

我想要实现的是,希望将此查询存储在某个属性文件或数据库本身中,并根据某些逻辑获取查询字符串并执行它。 在 Java 中,我能够做到这一点。我可以将所有应用程序查询存储在属性文件中,以便在查询需要更新时避免编译整个应用程序。

可以在 NodeJs 中实现类似的功能。我正在使用 Mongoose 连接 MongoDB? 到目前为止,我能够实现的是,我能够将上述查询存储在 MongoDB 中并获取变量中的字符串。

queryGetter = await Queries.find()
const queryString = queryGetter.qstring             // storing query string
queryRes = await Seller.aggregate(queryString)

但这会报错

"Error: Arguments must be aggregate pipeline operators"

提前感谢任何线索来实现这一点

【问题讨论】:

  • 如果您将json字符串存储在db中并检索,那么您需要解析字符串JSON.parse(queryString)
  • JSON.parse(queryString) 给出了更多错误,它不接受 $match:{}

标签: node.js mongodb


【解决方案1】:

如果您已正确插入字符串化查询,如下所示:

let string_query = JSON.stringify(Your Query Object);

然后就可以解析了,如下:

let object_query = JSON.parse(string_query);

您的查询的工作示例:

// YOUR ORIGINAL QUERY
let original_query = [
        {$match: {}},{$addFields : {"communication_information":{$filter:{ input: "$communication_information",as: "communication_information",
             cond: {"$or" :[{$eq: ["$$communication_information.communication_information_type",  "phone"  ] },
                      {$eq: ["$$communication_information.communication_information_type", "email"] },
                      ]}}}}},{ "$project": {"_id": 1,"initial_name": 1,"first_name": 1,"last_name": 1,"gender":1,"communication_information":1, }},
                      { $sort : { first_name : 1, last_name: 1 } },];

// STRINGIFY QUERY FOR STORING IN DB PURPOSE
let string_query = JSON.stringify(original_query);

console.log("Stringiy Query: ", string_query);

// PARSE AGAIN WHEN YOU FETCH FROM DB
let parsed_query = JSON.parse(string_query);

console.log("Parsed Query: ", parsed_query);

如果您已经将查询存储在DB中并且在stringify中存在一些问题,因为查询过长会导致错误,您可以尝试db.command

【讨论】:

  • 感谢它的工作。当我从 mongodb 检索它但将其放入 .JSON 文件时,它以某种方式不起作用。
猜你喜欢
  • 1970-01-01
  • 2021-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-02
  • 2015-03-20
相关资源
最近更新 更多