Search code examples
mongodbaggregation-frameworkmongodb-java

In MongoDB aggregation pipeline, how to project a returned field into an array of that value


In MongoDB 3.6, if I am using the java driver and aggregating, after matching, how can I project a particular field of the results into a single-element array of that type? For example, one of my fields is a string, and I want to create a one-element string array so that I can perform a set union later between that value and a set (which is another value in the results).


Solution

  • You can try Projections.computed static method to output an array of single value.

    Something like

    Bson bson = computed("fname", Arrays.asList("$value"));
    

    Verify:

    BsonDocument bsonDocument = bson.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
    System.out.print(bsonDocument.toString());// { "fname" : ["$value"] }