Custom field into Aggregation with MONGO












0















Is it possible to add 2 custom fields (that are not exist at my collections), into aggregate group query, using java with mongoDB? My approach is below but it doesn't work



    Double custom_calculated_field1 = 0d;
Double custom_calculated_field2 = 0d;
Document customGroup_fields = new Document();
customGroup_fields.append("customer_id", "$customer_id");
//custom_calculated fields
customGroup_fields.append("custom_calculated_field1", custom_calculated_field1);
customGroup_fields.append("custom_calculated_field2", custom_calculated_field2);
AggregateIterable<Document> customers_results = customerID.aggregate(
Arrays.asList(
Aggregates.match(values),
Aggregates.group(customGroup_fields)
));









share|improve this question

























  • What is your document before and what would you like it to look like after? Also, the aggregation won't really "add" anything since it is only aggregating it. If you want to add fields you require a projection. Your code seems to be defining groupings?

    – pandaadb
    Nov 15 '18 at 13:32













  • Why do you have to add the custom fields to the group ? Can't you just add it to returned results ? Just trying to understand the use case. Btw what is not working when you try the way you have ?

    – Veeram
    Nov 15 '18 at 13:33











  • At the final, i want to return a json object, which contains user id and the two other custom fields grouped by user.

    – user2966853
    Nov 15 '18 at 13:39











  • I believe you are missing the keywords. An aggregation pipeline is undefined in terms of what has to happen first. So your match isn't really a match and your grouping is not a group. You need to tell the pipeline what it is meant to do. I have an example using DBObjects, not one with Documents. If you want i can post that

    – pandaadb
    Nov 15 '18 at 13:48


















0















Is it possible to add 2 custom fields (that are not exist at my collections), into aggregate group query, using java with mongoDB? My approach is below but it doesn't work



    Double custom_calculated_field1 = 0d;
Double custom_calculated_field2 = 0d;
Document customGroup_fields = new Document();
customGroup_fields.append("customer_id", "$customer_id");
//custom_calculated fields
customGroup_fields.append("custom_calculated_field1", custom_calculated_field1);
customGroup_fields.append("custom_calculated_field2", custom_calculated_field2);
AggregateIterable<Document> customers_results = customerID.aggregate(
Arrays.asList(
Aggregates.match(values),
Aggregates.group(customGroup_fields)
));









share|improve this question

























  • What is your document before and what would you like it to look like after? Also, the aggregation won't really "add" anything since it is only aggregating it. If you want to add fields you require a projection. Your code seems to be defining groupings?

    – pandaadb
    Nov 15 '18 at 13:32













  • Why do you have to add the custom fields to the group ? Can't you just add it to returned results ? Just trying to understand the use case. Btw what is not working when you try the way you have ?

    – Veeram
    Nov 15 '18 at 13:33











  • At the final, i want to return a json object, which contains user id and the two other custom fields grouped by user.

    – user2966853
    Nov 15 '18 at 13:39











  • I believe you are missing the keywords. An aggregation pipeline is undefined in terms of what has to happen first. So your match isn't really a match and your grouping is not a group. You need to tell the pipeline what it is meant to do. I have an example using DBObjects, not one with Documents. If you want i can post that

    – pandaadb
    Nov 15 '18 at 13:48
















0












0








0








Is it possible to add 2 custom fields (that are not exist at my collections), into aggregate group query, using java with mongoDB? My approach is below but it doesn't work



    Double custom_calculated_field1 = 0d;
Double custom_calculated_field2 = 0d;
Document customGroup_fields = new Document();
customGroup_fields.append("customer_id", "$customer_id");
//custom_calculated fields
customGroup_fields.append("custom_calculated_field1", custom_calculated_field1);
customGroup_fields.append("custom_calculated_field2", custom_calculated_field2);
AggregateIterable<Document> customers_results = customerID.aggregate(
Arrays.asList(
Aggregates.match(values),
Aggregates.group(customGroup_fields)
));









share|improve this question
















Is it possible to add 2 custom fields (that are not exist at my collections), into aggregate group query, using java with mongoDB? My approach is below but it doesn't work



    Double custom_calculated_field1 = 0d;
Double custom_calculated_field2 = 0d;
Document customGroup_fields = new Document();
customGroup_fields.append("customer_id", "$customer_id");
//custom_calculated fields
customGroup_fields.append("custom_calculated_field1", custom_calculated_field1);
customGroup_fields.append("custom_calculated_field2", custom_calculated_field2);
AggregateIterable<Document> customers_results = customerID.aggregate(
Arrays.asList(
Aggregates.match(values),
Aggregates.group(customGroup_fields)
));






java mongodb






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 15 '18 at 14:59









CS_noob

4571311




4571311










asked Nov 15 '18 at 13:27









user2966853user2966853

213




213













  • What is your document before and what would you like it to look like after? Also, the aggregation won't really "add" anything since it is only aggregating it. If you want to add fields you require a projection. Your code seems to be defining groupings?

    – pandaadb
    Nov 15 '18 at 13:32













  • Why do you have to add the custom fields to the group ? Can't you just add it to returned results ? Just trying to understand the use case. Btw what is not working when you try the way you have ?

    – Veeram
    Nov 15 '18 at 13:33











  • At the final, i want to return a json object, which contains user id and the two other custom fields grouped by user.

    – user2966853
    Nov 15 '18 at 13:39











  • I believe you are missing the keywords. An aggregation pipeline is undefined in terms of what has to happen first. So your match isn't really a match and your grouping is not a group. You need to tell the pipeline what it is meant to do. I have an example using DBObjects, not one with Documents. If you want i can post that

    – pandaadb
    Nov 15 '18 at 13:48





















  • What is your document before and what would you like it to look like after? Also, the aggregation won't really "add" anything since it is only aggregating it. If you want to add fields you require a projection. Your code seems to be defining groupings?

    – pandaadb
    Nov 15 '18 at 13:32













  • Why do you have to add the custom fields to the group ? Can't you just add it to returned results ? Just trying to understand the use case. Btw what is not working when you try the way you have ?

    – Veeram
    Nov 15 '18 at 13:33











  • At the final, i want to return a json object, which contains user id and the two other custom fields grouped by user.

    – user2966853
    Nov 15 '18 at 13:39











  • I believe you are missing the keywords. An aggregation pipeline is undefined in terms of what has to happen first. So your match isn't really a match and your grouping is not a group. You need to tell the pipeline what it is meant to do. I have an example using DBObjects, not one with Documents. If you want i can post that

    – pandaadb
    Nov 15 '18 at 13:48



















What is your document before and what would you like it to look like after? Also, the aggregation won't really "add" anything since it is only aggregating it. If you want to add fields you require a projection. Your code seems to be defining groupings?

– pandaadb
Nov 15 '18 at 13:32







What is your document before and what would you like it to look like after? Also, the aggregation won't really "add" anything since it is only aggregating it. If you want to add fields you require a projection. Your code seems to be defining groupings?

– pandaadb
Nov 15 '18 at 13:32















Why do you have to add the custom fields to the group ? Can't you just add it to returned results ? Just trying to understand the use case. Btw what is not working when you try the way you have ?

– Veeram
Nov 15 '18 at 13:33





Why do you have to add the custom fields to the group ? Can't you just add it to returned results ? Just trying to understand the use case. Btw what is not working when you try the way you have ?

– Veeram
Nov 15 '18 at 13:33













At the final, i want to return a json object, which contains user id and the two other custom fields grouped by user.

– user2966853
Nov 15 '18 at 13:39





At the final, i want to return a json object, which contains user id and the two other custom fields grouped by user.

– user2966853
Nov 15 '18 at 13:39













I believe you are missing the keywords. An aggregation pipeline is undefined in terms of what has to happen first. So your match isn't really a match and your grouping is not a group. You need to tell the pipeline what it is meant to do. I have an example using DBObjects, not one with Documents. If you want i can post that

– pandaadb
Nov 15 '18 at 13:48







I believe you are missing the keywords. An aggregation pipeline is undefined in terms of what has to happen first. So your match isn't really a match and your grouping is not a group. You need to tell the pipeline what it is meant to do. I have an example using DBObjects, not one with Documents. If you want i can post that

– pandaadb
Nov 15 '18 at 13:48














1 Answer
1






active

oldest

votes


















0














This is a problem with the way you structure your aggregation. You can read more about it on the Mongo aggregation docs here: https://docs.mongodb.com/manual/aggregation/



Effectively you assume that your pipeline knows what operations you are trying to execute. A pipeline however works very similar to what a unix pipe | does. It executes any command and passes the output to the next. So you need to tell it that your match is a match and the group is a group. I have an example for both Document and DBObject, where DBObject is the more up to date approach I believe. Consider this example:



  @Test
public void testAggProjection() {
DBCollection collection = template.getCollection("test-collection");

DBObject ob = new BasicDBObject(ImmutableMap.of("test", "value1", "something", "here"));
DBObject ob2 = new BasicDBObject(ImmutableMap.of("test", "value1", "hello", "world"));
DBObject ob3 = new BasicDBObject(ImmutableMap.of("test", "value2", "other", "fields"));
WriteResult insert = collection.insert(ob, ob2, ob3);
Assert.assertEquals(3, insert.getN());

DBObject match = new BasicDBObject("$match", new BasicDBObject("test", "value1")); // match the test value
Map<String, Object> grouping = new HashMap<>();
grouping.put("_id", "$test");
grouping.put("my_count", new BasicDBObject("$sum", 1));
DBObject group = new BasicDBObject("$group", grouping); // group by

AggregationOutput aggregate = collection.aggregate(match, group);
System.out.println(aggregate.results());
DBObject next = aggregate.results().iterator().next();
Assert.assertTrue(next.containsField("_id"));
Assert.assertTrue(next.containsField("my_count"));


// with documents raw
MongoClient mc = (MongoClient) client;
MongoCollection<Document> collection2 = mc.getDatabase(template.getDb().getName()).getCollection("test-collection");

Document dob = new Document(ImmutableMap.of("test", "value1", "something", "here"));
Document dob2 = new Document(ImmutableMap.of("test", "value1", "hello", "world"));
Document dob3 = new Document(ImmutableMap.of("test", "value2", "other", "fields"));

collection2.insertMany(Arrays.asList(dob, dob2, dob3));

long count = collection2.count();
Assert.assertEquals(3, count);

Document match2 = new Document("$match", new Document("test", "value1"));
Document group2 = new Document("$group", ImmutableMap.of("_id", "$test", "my_count", new Document("$sum", 1)));

AggregateIterable<Document> aggregate2 = collection2.aggregate(Arrays.asList(match2, group2));
Document next2 = aggregate2.iterator().next();
Assert.assertTrue(next2.get("_id") != null);
Assert.assertTrue(next2.get("my_count") != null);
}


This is a working unit test. What this does is (in both cases):




  • Create a new collection and insert 3 documents.

  • Aggregate them with a match, matching 2 documents, and a group where we count the objects we found.


The important bits for you are here:



Document match2 = new Document("$match", new Document("test", "value1"));
Document group2 = new Document("$group", ImmutableMap.of("_id", "$test", "my_count", new Document("$sum", 1)));

AggregateIterable<Document> aggregate2 = collection2.aggregate(Arrays.asList(match2, group2));


In my match2 and group2 documents, I define what stage the aggregation is executing as $match and $group.



The resulting Json is then:



Document{{_id=value1, my_count=2}}


I hope that helps!



Please note that the _id field inside the group is mandatory.



Artur






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53320552%2fcustom-field-into-aggregation-with-mongo%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    This is a problem with the way you structure your aggregation. You can read more about it on the Mongo aggregation docs here: https://docs.mongodb.com/manual/aggregation/



    Effectively you assume that your pipeline knows what operations you are trying to execute. A pipeline however works very similar to what a unix pipe | does. It executes any command and passes the output to the next. So you need to tell it that your match is a match and the group is a group. I have an example for both Document and DBObject, where DBObject is the more up to date approach I believe. Consider this example:



      @Test
    public void testAggProjection() {
    DBCollection collection = template.getCollection("test-collection");

    DBObject ob = new BasicDBObject(ImmutableMap.of("test", "value1", "something", "here"));
    DBObject ob2 = new BasicDBObject(ImmutableMap.of("test", "value1", "hello", "world"));
    DBObject ob3 = new BasicDBObject(ImmutableMap.of("test", "value2", "other", "fields"));
    WriteResult insert = collection.insert(ob, ob2, ob3);
    Assert.assertEquals(3, insert.getN());

    DBObject match = new BasicDBObject("$match", new BasicDBObject("test", "value1")); // match the test value
    Map<String, Object> grouping = new HashMap<>();
    grouping.put("_id", "$test");
    grouping.put("my_count", new BasicDBObject("$sum", 1));
    DBObject group = new BasicDBObject("$group", grouping); // group by

    AggregationOutput aggregate = collection.aggregate(match, group);
    System.out.println(aggregate.results());
    DBObject next = aggregate.results().iterator().next();
    Assert.assertTrue(next.containsField("_id"));
    Assert.assertTrue(next.containsField("my_count"));


    // with documents raw
    MongoClient mc = (MongoClient) client;
    MongoCollection<Document> collection2 = mc.getDatabase(template.getDb().getName()).getCollection("test-collection");

    Document dob = new Document(ImmutableMap.of("test", "value1", "something", "here"));
    Document dob2 = new Document(ImmutableMap.of("test", "value1", "hello", "world"));
    Document dob3 = new Document(ImmutableMap.of("test", "value2", "other", "fields"));

    collection2.insertMany(Arrays.asList(dob, dob2, dob3));

    long count = collection2.count();
    Assert.assertEquals(3, count);

    Document match2 = new Document("$match", new Document("test", "value1"));
    Document group2 = new Document("$group", ImmutableMap.of("_id", "$test", "my_count", new Document("$sum", 1)));

    AggregateIterable<Document> aggregate2 = collection2.aggregate(Arrays.asList(match2, group2));
    Document next2 = aggregate2.iterator().next();
    Assert.assertTrue(next2.get("_id") != null);
    Assert.assertTrue(next2.get("my_count") != null);
    }


    This is a working unit test. What this does is (in both cases):




    • Create a new collection and insert 3 documents.

    • Aggregate them with a match, matching 2 documents, and a group where we count the objects we found.


    The important bits for you are here:



    Document match2 = new Document("$match", new Document("test", "value1"));
    Document group2 = new Document("$group", ImmutableMap.of("_id", "$test", "my_count", new Document("$sum", 1)));

    AggregateIterable<Document> aggregate2 = collection2.aggregate(Arrays.asList(match2, group2));


    In my match2 and group2 documents, I define what stage the aggregation is executing as $match and $group.



    The resulting Json is then:



    Document{{_id=value1, my_count=2}}


    I hope that helps!



    Please note that the _id field inside the group is mandatory.



    Artur






    share|improve this answer




























      0














      This is a problem with the way you structure your aggregation. You can read more about it on the Mongo aggregation docs here: https://docs.mongodb.com/manual/aggregation/



      Effectively you assume that your pipeline knows what operations you are trying to execute. A pipeline however works very similar to what a unix pipe | does. It executes any command and passes the output to the next. So you need to tell it that your match is a match and the group is a group. I have an example for both Document and DBObject, where DBObject is the more up to date approach I believe. Consider this example:



        @Test
      public void testAggProjection() {
      DBCollection collection = template.getCollection("test-collection");

      DBObject ob = new BasicDBObject(ImmutableMap.of("test", "value1", "something", "here"));
      DBObject ob2 = new BasicDBObject(ImmutableMap.of("test", "value1", "hello", "world"));
      DBObject ob3 = new BasicDBObject(ImmutableMap.of("test", "value2", "other", "fields"));
      WriteResult insert = collection.insert(ob, ob2, ob3);
      Assert.assertEquals(3, insert.getN());

      DBObject match = new BasicDBObject("$match", new BasicDBObject("test", "value1")); // match the test value
      Map<String, Object> grouping = new HashMap<>();
      grouping.put("_id", "$test");
      grouping.put("my_count", new BasicDBObject("$sum", 1));
      DBObject group = new BasicDBObject("$group", grouping); // group by

      AggregationOutput aggregate = collection.aggregate(match, group);
      System.out.println(aggregate.results());
      DBObject next = aggregate.results().iterator().next();
      Assert.assertTrue(next.containsField("_id"));
      Assert.assertTrue(next.containsField("my_count"));


      // with documents raw
      MongoClient mc = (MongoClient) client;
      MongoCollection<Document> collection2 = mc.getDatabase(template.getDb().getName()).getCollection("test-collection");

      Document dob = new Document(ImmutableMap.of("test", "value1", "something", "here"));
      Document dob2 = new Document(ImmutableMap.of("test", "value1", "hello", "world"));
      Document dob3 = new Document(ImmutableMap.of("test", "value2", "other", "fields"));

      collection2.insertMany(Arrays.asList(dob, dob2, dob3));

      long count = collection2.count();
      Assert.assertEquals(3, count);

      Document match2 = new Document("$match", new Document("test", "value1"));
      Document group2 = new Document("$group", ImmutableMap.of("_id", "$test", "my_count", new Document("$sum", 1)));

      AggregateIterable<Document> aggregate2 = collection2.aggregate(Arrays.asList(match2, group2));
      Document next2 = aggregate2.iterator().next();
      Assert.assertTrue(next2.get("_id") != null);
      Assert.assertTrue(next2.get("my_count") != null);
      }


      This is a working unit test. What this does is (in both cases):




      • Create a new collection and insert 3 documents.

      • Aggregate them with a match, matching 2 documents, and a group where we count the objects we found.


      The important bits for you are here:



      Document match2 = new Document("$match", new Document("test", "value1"));
      Document group2 = new Document("$group", ImmutableMap.of("_id", "$test", "my_count", new Document("$sum", 1)));

      AggregateIterable<Document> aggregate2 = collection2.aggregate(Arrays.asList(match2, group2));


      In my match2 and group2 documents, I define what stage the aggregation is executing as $match and $group.



      The resulting Json is then:



      Document{{_id=value1, my_count=2}}


      I hope that helps!



      Please note that the _id field inside the group is mandatory.



      Artur






      share|improve this answer


























        0












        0








        0







        This is a problem with the way you structure your aggregation. You can read more about it on the Mongo aggregation docs here: https://docs.mongodb.com/manual/aggregation/



        Effectively you assume that your pipeline knows what operations you are trying to execute. A pipeline however works very similar to what a unix pipe | does. It executes any command and passes the output to the next. So you need to tell it that your match is a match and the group is a group. I have an example for both Document and DBObject, where DBObject is the more up to date approach I believe. Consider this example:



          @Test
        public void testAggProjection() {
        DBCollection collection = template.getCollection("test-collection");

        DBObject ob = new BasicDBObject(ImmutableMap.of("test", "value1", "something", "here"));
        DBObject ob2 = new BasicDBObject(ImmutableMap.of("test", "value1", "hello", "world"));
        DBObject ob3 = new BasicDBObject(ImmutableMap.of("test", "value2", "other", "fields"));
        WriteResult insert = collection.insert(ob, ob2, ob3);
        Assert.assertEquals(3, insert.getN());

        DBObject match = new BasicDBObject("$match", new BasicDBObject("test", "value1")); // match the test value
        Map<String, Object> grouping = new HashMap<>();
        grouping.put("_id", "$test");
        grouping.put("my_count", new BasicDBObject("$sum", 1));
        DBObject group = new BasicDBObject("$group", grouping); // group by

        AggregationOutput aggregate = collection.aggregate(match, group);
        System.out.println(aggregate.results());
        DBObject next = aggregate.results().iterator().next();
        Assert.assertTrue(next.containsField("_id"));
        Assert.assertTrue(next.containsField("my_count"));


        // with documents raw
        MongoClient mc = (MongoClient) client;
        MongoCollection<Document> collection2 = mc.getDatabase(template.getDb().getName()).getCollection("test-collection");

        Document dob = new Document(ImmutableMap.of("test", "value1", "something", "here"));
        Document dob2 = new Document(ImmutableMap.of("test", "value1", "hello", "world"));
        Document dob3 = new Document(ImmutableMap.of("test", "value2", "other", "fields"));

        collection2.insertMany(Arrays.asList(dob, dob2, dob3));

        long count = collection2.count();
        Assert.assertEquals(3, count);

        Document match2 = new Document("$match", new Document("test", "value1"));
        Document group2 = new Document("$group", ImmutableMap.of("_id", "$test", "my_count", new Document("$sum", 1)));

        AggregateIterable<Document> aggregate2 = collection2.aggregate(Arrays.asList(match2, group2));
        Document next2 = aggregate2.iterator().next();
        Assert.assertTrue(next2.get("_id") != null);
        Assert.assertTrue(next2.get("my_count") != null);
        }


        This is a working unit test. What this does is (in both cases):




        • Create a new collection and insert 3 documents.

        • Aggregate them with a match, matching 2 documents, and a group where we count the objects we found.


        The important bits for you are here:



        Document match2 = new Document("$match", new Document("test", "value1"));
        Document group2 = new Document("$group", ImmutableMap.of("_id", "$test", "my_count", new Document("$sum", 1)));

        AggregateIterable<Document> aggregate2 = collection2.aggregate(Arrays.asList(match2, group2));


        In my match2 and group2 documents, I define what stage the aggregation is executing as $match and $group.



        The resulting Json is then:



        Document{{_id=value1, my_count=2}}


        I hope that helps!



        Please note that the _id field inside the group is mandatory.



        Artur






        share|improve this answer













        This is a problem with the way you structure your aggregation. You can read more about it on the Mongo aggregation docs here: https://docs.mongodb.com/manual/aggregation/



        Effectively you assume that your pipeline knows what operations you are trying to execute. A pipeline however works very similar to what a unix pipe | does. It executes any command and passes the output to the next. So you need to tell it that your match is a match and the group is a group. I have an example for both Document and DBObject, where DBObject is the more up to date approach I believe. Consider this example:



          @Test
        public void testAggProjection() {
        DBCollection collection = template.getCollection("test-collection");

        DBObject ob = new BasicDBObject(ImmutableMap.of("test", "value1", "something", "here"));
        DBObject ob2 = new BasicDBObject(ImmutableMap.of("test", "value1", "hello", "world"));
        DBObject ob3 = new BasicDBObject(ImmutableMap.of("test", "value2", "other", "fields"));
        WriteResult insert = collection.insert(ob, ob2, ob3);
        Assert.assertEquals(3, insert.getN());

        DBObject match = new BasicDBObject("$match", new BasicDBObject("test", "value1")); // match the test value
        Map<String, Object> grouping = new HashMap<>();
        grouping.put("_id", "$test");
        grouping.put("my_count", new BasicDBObject("$sum", 1));
        DBObject group = new BasicDBObject("$group", grouping); // group by

        AggregationOutput aggregate = collection.aggregate(match, group);
        System.out.println(aggregate.results());
        DBObject next = aggregate.results().iterator().next();
        Assert.assertTrue(next.containsField("_id"));
        Assert.assertTrue(next.containsField("my_count"));


        // with documents raw
        MongoClient mc = (MongoClient) client;
        MongoCollection<Document> collection2 = mc.getDatabase(template.getDb().getName()).getCollection("test-collection");

        Document dob = new Document(ImmutableMap.of("test", "value1", "something", "here"));
        Document dob2 = new Document(ImmutableMap.of("test", "value1", "hello", "world"));
        Document dob3 = new Document(ImmutableMap.of("test", "value2", "other", "fields"));

        collection2.insertMany(Arrays.asList(dob, dob2, dob3));

        long count = collection2.count();
        Assert.assertEquals(3, count);

        Document match2 = new Document("$match", new Document("test", "value1"));
        Document group2 = new Document("$group", ImmutableMap.of("_id", "$test", "my_count", new Document("$sum", 1)));

        AggregateIterable<Document> aggregate2 = collection2.aggregate(Arrays.asList(match2, group2));
        Document next2 = aggregate2.iterator().next();
        Assert.assertTrue(next2.get("_id") != null);
        Assert.assertTrue(next2.get("my_count") != null);
        }


        This is a working unit test. What this does is (in both cases):




        • Create a new collection and insert 3 documents.

        • Aggregate them with a match, matching 2 documents, and a group where we count the objects we found.


        The important bits for you are here:



        Document match2 = new Document("$match", new Document("test", "value1"));
        Document group2 = new Document("$group", ImmutableMap.of("_id", "$test", "my_count", new Document("$sum", 1)));

        AggregateIterable<Document> aggregate2 = collection2.aggregate(Arrays.asList(match2, group2));


        In my match2 and group2 documents, I define what stage the aggregation is executing as $match and $group.



        The resulting Json is then:



        Document{{_id=value1, my_count=2}}


        I hope that helps!



        Please note that the _id field inside the group is mandatory.



        Artur







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 15 '18 at 14:12









        pandaadbpandaadb

        4,59611225




        4,59611225
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53320552%2fcustom-field-into-aggregation-with-mongo%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python