12
[
  {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.

1 Answer 1

24

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

db.collection.aggregate([
    {$project: {"lecture": {$arrayElemAt:[{$split: ["$lecture" , "#"]}, 0]}}}
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.