Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$split and return the first array element in mongodb query

[
  {lecture : "427#Math"},
  {lecture : "217#Science"},
  {lecture : "7#History"},
  {lecture : "12#Music"}
]

Assume I have the database structure above. I want to return only the lecture code. What have I done so far?

db.collection.aggregate([
    {$project: {"lecture": {$split: ["$lecture" , "#"]}}}
])

But this returns as collection ["427" , "Math"]. How can I return only the lecture code which is the part that comes before the # character.

like image 386
mmu36478 Avatar asked Apr 25 '17 08:04

mmu36478


1 Answers

You can use $arrayElemAt to return only first item from $split result:

db.collection.aggregate([
    {$project: {"lecture": {$arrayElemAt:[{$split: ["$lecture" , "#"]}, 0]}}}
])
like image 159
Alex Blex Avatar answered Nov 15 '22 07:11

Alex Blex