2017-04-25 101 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]}}} 
]) 
相關問題