user3383301
user3383301

Reputation: 1911

Change alias name for a field in Mongo Query

When i execute the below query, i get proper response

db.getCollection('register').aggregate( [
  { $match: {"$or":[{"$and":[{"src":{"$in":["CR","FR"]}},{"status":{"$in":["Draft","InReview","Returned"]}},{kid:3940035}]}]} },
  { $group: {'_id':"$kid",'count':{'$sum':1}} }
] )

But I need to display kid as knowledge_id. So if the change from _id to knowledge_id the query returns an error as

The field 'knowledge_id' must be an accumulator object' on server

Updated Query :

db.getCollection('register').aggregate( [
      { $match: {"$or":[{"$and":[{"src":{"$in":["CR","FR"]}},{"status":{"$in":["Draft","InReview","Returned"]}},{kid:3940035}]}]} },
      { $group: {'knowledge_id':"$kid",'count':{'$sum':1}} }
    ] )

Please help !!

Upvotes: 0

Views: 873

Answers (1)

R2D2
R2D2

Reputation: 10727

You can just add one more stage after the grouping ( grouping require always _id to be present ) :

 {$project:{"knowledge_id":"$_id", count:1}}

Upvotes: 1

Related Questions