MongoDB / Mongoose查询基于多个子文档

时间:2017-05-03 17:26:56

标签: mongodb mongoose mongodb-query aggregation-framework mean-stack

我是MongoDB和Mongoose的新手。我目前正在构建一个应用程序,其客户端集合包含客户端拥有的一系列帐户。

我想根据客户拥有的帐户的具体情况来查询集合。例如,我需要返回以下客户端:

  • clientType:"标准"
  • 有两个帐户:
    • accountType:" FML",余额:$ gt 3000
    • accountType:" OMG",余额:$ lt 3000

以下是示例文档:

CMake Error at C:/Users/Lelek/dlib-19.4/dlib/cmake_utils/add_python_module:116 (message):
   Boost python library not found.
Call Stack (most recent call first):
  CMakeLists.txt:6 (include)

-- Configuring incomplete, errors occurred!
See also "C:/Users/Lelek/dlib-19.4/tools/python/build/CMakeFiles/CMakeOutput.log".

error: cmake configuration failed!

到目前为止,我只是想出了如何构建一个可以获得clientType" Standard"的客户端的查询。 with accountTypes [" FML"," OMG]但我无法弄清楚如何为特定帐户类型指定余额条件。

{
    clientDetails: {
        cardNumber: "0123456",
        firstName: "Bob",
        lastName: "Dole",
        clientType: "Standard"
    },
    accounts: [
        {
            accountNumber: "123",
            accountType: "FML",
            balance: 4000.00
        },
        {
            accountNumber: "234",
            accountType: "OMG",
            balance: 2000
        }
    ]
}

1 个答案:

答案 0 :(得分:1)

您可以将$all$elemMatch一起使用。

ClientModel
    .find({
        "clientDetails.clientType": "Standard",
        "accounts": 
          { 
             $all: [
                     { "$elemMatch" : { accountType: "FML", balance: { $gt: 3000} } },
                     { "$elemMatch" : { accountType: "OMG", balance: { $lt: 3000} } } 
               ]
          }
    })
    .then(
        function(){ //etc..},
        function(err){ //etc...}
    );