@@ -250,6 +250,12 @@ Learn [when to use $addFields over $project](https://www.practical-mongodb-aggre
250250 <TabItem value = " project" label = " Using $project" >
251251 <div >
252252 ``` java
253+ import com.mongodb.client.model.Projections ;
254+ import com.mongodb.client.model.Field ;
255+ import com.mongodb.client.model.Sorts ;
256+ import static com.mongodb.client.model.Filters.exists ;
257+ import static com.mongodb.client.model.Filters.gt ;
258+
253259 books. aggregate(
254260 List . of(
255261 Aggregates . match(gt(" year" , 2000 )),
@@ -275,21 +281,27 @@ Learn [when to use $addFields over $project](https://www.practical-mongodb-aggre
275281 <TabItem value = " addFields" label = " Using $addFields" >
276282 <div >
277283 ``` java
284+ import com.mongodb.client.model.Projections ;
285+ import com.mongodb.client.model.Field ;
286+ import com.mongodb.client.model.Sorts ;
287+ import static com.mongodb.client.model.Filters.exists ;
288+ import static com.mongodb.client.model.Filters.gt ;
289+
278290 books. aggregate(
279291 List . of(
280- Aggregates . match(gt(" year" , 2000 )),
281- Aggregates . match(exists(" authors" , true )),
282- Aggregates . addFields(
283- new Field<> (
284- " numAuthors" ,
285- new Document (" $size" , " $authors" )
286- )
287- ),
288- Aggregates . project(
289- Projections . fields(
290- Projections . include(" title" , " year" , " authors" , " numAuthors" ))),
291- Aggregates . sort(Sorts . descending(" numAuthors" )),
292- Aggregates . limit(1 )
292+ Aggregates . match(gt(" year" , 2000 )),
293+ Aggregates . match(exists(" authors" , true )),
294+ Aggregates . addFields(
295+ new Field<> (
296+ " numAuthors" ,
297+ new Document (" $size" , " $authors" )
298+ )
299+ ),
300+ Aggregates . project(
301+ Projections . fields(
302+ Projections . include(" title" , " year" , " authors" , " numAuthors" ))),
303+ Aggregates . sort(Sorts . descending(" numAuthors" )),
304+ Aggregates . limit(1 )
293305 )
294306 ). forEach(c - > System . out. println(c. toJson()));
295307 ```
0 commit comments