mongoTemplateとDbRefフィールドのモンゴ集約

ショックSeneviratne:

次のように私は2つのmongoのコレクションを持っていると仮定します。

Collection A
{ 
    "_id" : ObjectId("582abcd85d2dfa67f44127e0"),
    "level" : "super"
    "dataReference" : Object
        B : DbRef(B, 5b618a570550de0021aaa2ef, undefined)
}

Collection B
{ 
    "_id" : ObjectId("5b618a570550de0021aaa2ef"),  
    "role" : "admin"
}

私は必要なのレコードは、「管理者」として、「スーパー」とその関連コレクションBのレコードの「役割」の値として「レベル」フィールドの値を持っている、コレクションAからレコードを取得しています。

このために、私は、集約およびJava mongoTemplateを使用しようとしています。

以下は、私が試したことのコードですが、それは0のレコードを返します。

final TypedAggregation<A> typedAggregation = Aggregation.newAggregation(A.class,
                Aggregation.match(Criteria.where("level").equals(level)),
                Aggregation.lookup("B", "_id", "dataReference.B.$id", "Basb"),
                Aggregation.match(new Criteria().andOperator(
                        Criteria.where("B.role").regex("admin")
                )));

        final AggregationResults<Map> A = mongoTemplate.aggregate(typedAggregation, "A", Map.class);

私はMongoの集約に新しいですのでご注意ください。

Valijon:

それは静かな醜いソリューションです。

MongoTemplate

あなたは使用することはできませんTypedAggregation我々は変換する必要があるためAで参加できるようにするコレクションをB収集

Aggregation typedAggregation = Aggregation.newAggregation(
    Aggregation.match(Criteria.where("level").is("super")),
    new AggregationOperation() {
        @Override
        public Document toDocument(AggregationOperationContext context) {
            return Document.parse("{\"$addFields\":{\"dataReference\":{\"$reduce\":{\"input\":{\"$objectToArray\":\"$dataReference\"},\"initialValue\":null,\"in\":{\"$cond\":[{\"$eq\":[{\"$type\":\"$$this.v\"},\"objectId\"]},\"$$this.v\",\"$$value\"]}}}}}");
        }
    },
    Aggregation.lookup("B", "dataReference", "_id", "B"),
    Aggregation.match(new Criteria().andOperator(
             Criteria.where("B.role").regex("admin")
        )
    )
);

final AggregationResults<Document> A = mongoTemplate.aggregate(typedAggregation, "A", Document.class);

MongoDBの集計

db.A.aggregate([
  {
    "$match": {
      "level": "super"
    }
  },
  {
    "$addFields": {
      "B": {
        "$reduce": {
          "input": {
            "$objectToArray": "$dataReference"
          },
          "initialValue": null,
          "in": {
            "$cond": [
              {
                "$eq": [
                  {
                    "$type": "$$this.v"
                  },
                  "objectId"
                ]
              },
              "$$this.v",
              "$$value"
            ]
          }
        }
      }
    }
  },
  {
    "$lookup": {
      "from": "B",
      "localField": "B",
      "foreignField": "_id",
      "as": "B"
    }
  },
  {
    "$match": {
      "$and": [
        {
          "B.role": {
            "$regex": "admin",
            "$options": ""
          }
        }
      ]
    }
  }
])

MongoPlayground

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=301206&siteId=1