$ split and returns the first element of the array in the mongodb request

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

Suppose 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 it comes back as a collection ["427" , "Math"]. How can I return only the lecture code, which is the part that precedes the character #.

+4
source share
1 answer

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

db.collection.aggregate([
    {$project: {"lecture": {$arrayElemAt:[{$split: ["$lecture" , "#"]}, 0]}}}
])
+6
source

Source: https://habr.com/ru/post/1675594/


All Articles