Real Dreams
Real Dreams

Reputation: 18010

Retrieving just a part of a field

Is it possible to retrieve a part of a filed using RegEx or any other way in Mongodb, for example consider following collection.

values of field x 
------------
XXaaaaa(dd)
YYaa(bb)aa
ZZxsf(ss)a

How can we can dd,bb,cc or how can we get XX,YY,ZZ?

I mean using Mongodb facilities, not js that executes not so fast. In SQL this can be done so easily but what about mongodb?

desired result 1
----------------
XX
YY
ZZ

desired result 2
----------------
dd
bb
ss

Upvotes: 1

Views: 62

Answers (1)

Aravind Yarram
Aravind Yarram

Reputation: 80176

I think you can use the aggregation framework and $substr for this. Sample (didn't verify) assuming the data is in the "abc" property.

db.collection1.aggregate({ 
  $project: { 
    : { $substr: ["$abc", 0, 2] } 
  }
});

Upvotes: 1

Related Questions