【问题标题】:Mongodb query array element meet criteriaMongodb查询数组元素满足条件
【发布时间】:2017-08-09 20:24:16
【问题描述】:

我有一个这样的文件:

solution:{
   "name":"solution name",
   "desc":"description",
   "case":[
          {
          "A":13,
          "B":"aaaa"
          },
          {
          "A":14,
          "B":"aaaa"
          },
          {
          "A":13,
          "B":"bbbb"
          }
   ]
}

案例是解决方案表中的一个数组字段,它包含两个字段,字段A和字段B。

现在我可以查询解决方案记录,返回结果将包含所有案例元素。现在我希望查询结果只包含字段B为“aaaa”的case元素,如何在java或MongoDB中编写查询?

我预期的查询结果应该是这样的:

solution:{
   "name":"solution name",
   "desc":"description",
   "case":[
          {
          "A":13,
          "B":"aaaa"
          },
          {
          "A":14,
          "B":"aaaa"
          },
   ]
}

【问题讨论】:

标签: java arrays mongodb


【解决方案1】:

您可以使用$filter aggregation 在投影期间根据条件过滤数组

db.solution.aggregate([
    {$match: {'case.B': "aaaa"}},
    {$project: {
        case: {$filter: {
            input: '$case',
            as: 'case',
            cond: {$eq: ['$$case.B', "aaaa"]}
        }},
        name:1,
        desc:1
    }}
])

【讨论】:

    【解决方案2】:

    您可以使用聚合管道 $redact 仅保留匹配的对象,

    Mongo shell 命令,

        db.solution.aggregate([ {$redact: {
            "$cond": [{
    
                    "$eq": [{
                            "$ifNull": ["$B", "aaaa"]
                        },
                        "aaaa"
                    ]
    
            }, "$$DESCEND", "$$PRUNE"]
        }}]).pretty()
    

    Mongo Java 代码,

            MongoClient client = new MongoClient("localhost");
            MongoDatabase db = client.getDatabase("Test"); 
            MongoCollection<Document> collection = db.getCollection("solution");
            List<Document> results = collection.aggregate(Arrays.asList(
                  new Document("$redact", new Document("$cond",
                          Arrays.asList(new Document("$eq",
                                  Arrays.asList(new Document("$ifNull", Arrays.asList("$B", "aaaa")), "aaaa")), 
                          "$$DESCEND", "$$PRUNE")))
    
            )).into(new ArrayList<Document>());
    
            for(Document docs: results){
              System.out.println(docs.toJson());
            }
    

    【讨论】:

    • 验证了您对 mongodb 命令的回答。需要了解一下,非常感谢,很有用。
    • 我们可以添加条件:db.solution.aggregate([ {$match:{"name":"solution name"}}, {$redact: { "$cond": [{ "$ eq": [{ "$ifNull": ["$B", "aaaa"] }, "aaaa" ] }, "$$DESCEND", "$$PRUNE"] }}]).pretty()跨度>
    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 2011-04-16
    • 2021-12-15
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多