removing duplicate array values from mongodb

前端 未结 2 822
灰色年华
灰色年华 2021-01-14 14:55

In mongodb I have collection where arrays has duplicate entries like

{
    \"_id\": ObjectId(\"57cf3cdd5f20a3b0ba009777\"),
    \"Chat\": 6,
    \"string\":          


        
2条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 15:09

    db.getCollection('Test').aggregate([{
        $unwind: '$string'},
        {
            $group: {
                _id: '$_id', 
                string: {
                    $addToSet: '$string'
                }, 
                Chat: {
                    $first: '$Chat'
                }
            }
        }
        ]);
    

    O/P: here you are getting 2 "1348157031 Riyadh" because there is an extra space which defines itself as an different entity.

    {
        "_id" : ObjectId("57cf3cdd5f20a3b0ba009777"),
        "string" : [ 
            " 1348157031 Riyadh", 
            " 548275320 Mohammad Sumon", 
            "1348157031 Riyadh"
        ],
        "Chat" : 6
    }
    

提交回复
热议问题