Artem Mezhenin
Artem Mezhenin

Reputation: 5757

Get substrings from field in MongoDB

I have collection with information about applications. Each document have field ver which holds version of application. Examples:

"1.0.0.2" (they are strings)
"2.0.3.10"
"3.1.5.111"

First 3 digints is major version, and last number is build version. I wander, is there any way I can get group by major version of application?

Example

Input collection:

{_id: ..., ver: "1.0.0.1"}, 
{_id: ..., ver: "1.0.0.2"}, 
{_id: ..., ver: "2.2.3.0"}

Aggregation result:

[ 
 {ver:"1.0.0", count:2},
 {ver:"2.2.3", count:1}
]

P.S. I'd prefer solution with Aggregation Framework :)

Upvotes: 4

Views: 4183

Answers (1)

Parvin Gasimzade
Parvin Gasimzade

Reputation: 26012

You can do it by using $substr operator. Following code will do what you want.

db.myCollection.aggregate({$group: {_id : {$substr : ["$ver", 0,5]}, count:{"$sum" : 1}}});

Response will be as follows :

[
  {"_id" : "1.0.0", "count" : 2},
  {"_id" : "2.2.3", "count" : 1}
]

Upvotes: 4

Related Questions