如何从MongoDB使用Mongoose和node.js检索数据

时间:2019-01-21 06:02:12

标签: node.js mongodb mongoose

我需要根据用户输入使用mongoose and Node.js来检索文档mongoDB。我在下面解释我的collection schema

{
  zone_list: [{
    zone: NORTH,
    state_list: [{    
      state: DELHI,
      location_list: [{
        location: NEW DELHI,
        task_list: [{
          user_pkId: 5c407834953d7f420d56f866,
          front_end_manager_name: SONAL,
          collection_manager: "",
          area_collection_manager: ASHIS JENA,
          loan_accounts_assigned: [{
            allocated_to: FIELD,
            lk_loan_account_id: LK0000015094,
            cl_contract_id: LAI-00016881,
            customer_name: REET INFOTECH,
            customer_bank_name: YES BANK,
          }]
        }]
      }]
    },{
      state: JK,
      location_list: [{
        location: Sree Nagar,
        task_list: [{
          user_pkId: 5c407834953d7f420d56f867,
          front_end_manager_name: SONAL,
          collection_manager: "",
          area_collection_manager: ASHIS JENA,
          loan_accounts_assigned: [{
            allocated_to: FIELD,
            lk_loan_account_id: LK0000015094,
            cl_contract_id: LAI-00016881,
            customer_name: REET INFOTECH,
            customer_bank_name: Corporate BANK,
          }]
        }]
      }]
    }]
  },{
    zone: EAST,
    state_list: [{    
      state: Odisha,
      location_list: [{
        location: Bhubaneswar,
        task_list: [{
          user_pkId: 5c407834953d7f420d56f868,
          front_end_manager_name: SONAL,
          collection_manager: "",
          area_collection_manager: ASHIS JENA,
          loan_accounts_assigned: [{
            allocated_to: FIELD,
            lk_loan_account_id: LK0000015094,
            cl_contract_id: LAI-00016881,
            customer_name: REET INFOTECH,
            customer_bank_name: SBI BANK,
          }]
        }]
      }]
    }]
  }]
}

在这里,我有上面的一个文档,其中包含多个区域,状态等。我需要根据zone,state,locations...etc提取相应的记录。我正在使用如下查询。

var zone = req.body.zone;
var allction = db.model("Allocation", alloc);
allction.connection.find({zone: zone}, function(err, docs) {
   if (!err) {
      res.send(docs);
   }
})

但是在这里我没有得到预期的输出。我需要使用zone输入,我应该使用zone and state类似地获取相关记录,我应该获取相应的输出。

1 个答案:

答案 0 :(得分:0)

因此,根据您的要求,您想首先从文档中找到区域。

您可以使用positional operator($)做这样的事情:

allction.connection.find({"zone_list.zone":zone},{projection:{
"zone_list.$":1
//list other fields what you want to select or project
}}).toArray(function(err,docs){
        if (!err) {
            res.send(docs);
        }
})

此外,如果您想使用汇总查询进行操作,则会更像这样:

allction.collection
  .aggregate([
    { $match: {} },
    { $unwind: "$zone_list" },
    { $unwind: "$zone_list.state_list" },
    { $unwind: "$‌​zone_list.state_list.location_list" },
    {
      $match: {
        zone: zone,
        state: state,
        location: location
      }
    }
  ])
  .toArray((err, docs) => {});