Mongodb查询数组元素符合标准

时间:2017-03-18 07:32:05

标签: java arrays mongodb

我有这样的文件:

function pageLoad(sender, args) {
    if (args.get_isPartialLoad()) {
        //Here Your   $(document).ready(function () {

   }
}

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

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

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

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

2 个答案:

答案 0 :(得分:0)

您可以使用聚合管道$ 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());
        }

答案 1 :(得分:0)

您可以使用$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
    }}
])