How to get the count value using $lookup in mongodb using golang?


Using aggregation I am joining two collections of mongodb using golang. The result is seems like below:-


{ "response": { "code": 1, "api_status": 1, "message": "Success", "total_record": [ { "_id": 1, "author_name": "mohit", "category": 232, "content": "This is the content", "date_time": 1524632713, "excerpt": "This is a short text", "image": "pic.jpg", "resultField": [ { "_id": 6, "comment": "this is a least comment", "comment_on": 1524644601, "email": "puneet@bookingkoala.com", "name": "puneet", "post_id": 1, "reply_to": 1524644601, "status": 1 }, { "_id": 7, "comment": "this is a least comment", "comment_on": 1524647808, "email": "puneet@bookingkoala.com", "name": "puneet", "post_id": 1, "reply_to": 1524647808, "status": 1 } ], "status": 0, "tags": "this", "title": "how to do the code" }, { "_id": 2, "author_name": "mohit", "category": 232, "content": "This is the content", "date_time": 1524632713, "excerpt": "This is a short text", "image": "pic.jpg", "resultField": [ { "_id": 8, "comment": "this is a least comment", "comment_on": 1524648059, "email": "puneet@bookingkoala.com", "name": "puneet", "post_id": 2, "reply_to": 1524648059, "status": 1 } ], "status": 0, "tags": "this", "title": "how to do the code" }, { "_id": 3, "author_name": "puneet", "category": 2, "content": "this is content", "date_time": 1524641086, "excerpt": "this is excerpt", "image": "pic.jpg", "resultField": [], "status": 1, "tags": "go", "title": "how to do the code" } ] } }

This <strong>output</strong> is taken by the below code of golang:-

mongoSession := config.ConnectDb() collection := mongoSession.DB(config.Database).C(config.BlogCollection) pipeline := []bson.M{ bson.M{"$match": bson.M{}}, bson.M{"$lookup": bson.M{"from" : "comment", "localField" : "_id", "foreignField": "post_id","as": "resultField" }}, } fmt.Println(pipeline) pipe := collection.Pipe(pipeline) resp := []bson.M{} err = pipe.All(&resp) if err != nil { fmt.Println("Errored: %#v \n", err) } fmt.Println(resp) if err != nil { response = ResponseControllerList{ config.FailureCode, config.FailureFlag, config.FailureMsg, nil, nil, } } else { response = ResponseControllerList{ config.SuccessFlag, config.SuccessFlag, config.SuccessMsg, nil, resp, } }

Issue is:- I need only count of the data <strong>not</strong> the data. Means in the output as shown above there is the resultField in which data is show but I only need the count value like:- "resultField":[2] but it is showing the data. How can I will get the count values of the data in output. Thank you in advance.


So your aggregation actually returns all comment documents in the resultField field, which implicitly contains the number of results, it's a slice of which you can check the length in Go using the builtin len() function.

Since you only need the length (number of comment documents), that's why you want to only retrieve the size of this array. For that purpose you may use the <a href="https://docs.mongodb.com/manual/reference/operator/aggregation/addFields/" rel="nofollow">$addFields</a> stage to replace the resultField array with a number being the length of this array.

pipe := c.Pipe([]bson.M{ { "$lookup": bson.M{ "from": "comment", "localField": "_id", "foreignField": "post_id", "as": "resultField", }, }, { "$addFields": bson.M{ "resultField": bson.M{"$size": "$resultField"}, }, }, })

Note that $addFields stage is equivalent to a $project stage that explicitly specifies all existing fields in the input documents and adds the new fields. Available only since MongoDB version 3.4.


  • How to do static analysis for C++ code with Eclipse cdt?
  • Fill out custom field with used coupon code WooCommerce
  • To allocate or not to allocate. Invalid read of size 1 errors. [Staring for 2 hours]
  • How can I constrain a subview so that it cannot be dragged outside of it's parent view's b
  • Why do I get IPC delays on 20% busy machine
  • Installing apk on android device via ADB with Java program on Linux
  • thrift installation error
  • trouble referencing Windows Portable Device files in VBA?
  • creating buttons in skview to point to different scenes
  • pip installation of gmpy2
  • Error in IE11 caused by babel polyfill - delegate.iterator.return
  • Get frequency distribution of a decimal range in MySQL
  • Escape awk special character in Python
  • How to Export CSV file from ASP.NET core
  • MySQL Query Select where id does not exist in the JOIN table
  • Create a mobile app that just points to URL
  • Cycle R,G,B vales as HUE?
  • iOS - open another application that exists on the phone?
  • Eric5: The OK button of 'new project' dialog is disable
  • Google Apps Script fails to generate image from EmbeddedChartBuilder
  • Making Django.contrib.auth store plain-text password
  • Slick: How can I combine a SQL LIKE statement with a SQL IN statement
  • Unable to connect to AWS RDS through PDO
  • Auto send email based on the time and email address in database
  • How to display converted time zones in a 'generic week' (Sunday thru Saturday)?
  • Spotify cocoalibspotify offline status set to 1 but all tracks stuck at waiting
  • Controller or RestController
  • ASP.NET MVC 2 actions for the same route?
  • Separating definition/instantiation of template classes without 'extern'
  • Problems using phonegap / cordova file plugin part 2 - synchronicity
  • Ruby regex for matching simpliest Ruby's regexes
  • Typeahead.js does give me suggestions but doesn't select them
  • How to include associated objects using gon in Rails/jQuery
  • How to clear a browser cache in Protractor
  • calling IO Operations from thread in ruby c extension will cause ruby to hang
  • media foundation H264 decoder not working properly
  • Running R's aov() mixed effects model from Python using rpy2