2017-04-25 38 views
4
[ 
    {lecture : "427#Math"}, 
    {lecture : "217#Science"}, 
    {lecture : "7#History"}, 
    {lecture : "12#Music"} 
] 

假设我有上面的数据库结构。我只想返回讲座代码。 到目前为止我做了什么?

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

但是这返回作为集合["427" , "Math"]。我如何才能返回#字符之前的部分演讲代码。

回答

6

您可以使用$arrayElemAt$split结果只返回第一个项目:

db.collection.aggregate([ 
    {$project: {"lecture": {$arrayElemAt:[{$split: ["$lecture" , "#"]}, 0]}}} 
]) 
相关问题