【问题标题】:MongoDB/Mongoose query based on multiple subdocuments基于多个子文档的MongoDB/Mongoose查询
【发布时间】:2017-10-01 15:57:41
【问题描述】:

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

我想根据客户拥有的帐户的详细信息查询集合。比如我需要返回的客户端是:

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

以下是示例文档:

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

到目前为止,我只知道如何构建一个查询,该查询可以使用 accountTypes ["FML","OMG] 获取 clientType "Standard" 的客户端,但我不知道如何指定余额条件对于特定的 accountTypes。

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

【问题讨论】:

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


    【解决方案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...}
        );
    

    【讨论】:

    • 这很好用。谢谢!我忘了提到客户可能有很多帐户。是否可以过滤掉不符合这些条件的帐户?
    • Np。我认为您无法使用常规查询。您可能必须使用聚合管道。看看这是否有帮助stackoverflow.com/questions/15117030/…
    • 感谢您的帮助!我去看看。
    猜你喜欢
    • 2020-08-02
    • 1970-01-01
    • 2019-07-27
    • 1970-01-01
    • 2017-02-27
    • 2015-04-27
    • 2018-04-05
    • 2013-03-04
    • 2020-07-16
    相关资源
    最近更新 更多