powerPixie
powerPixie

Reputation: 708

Find all distinct values for the first position in an array in a MongoDb document

There is an array field in the documents in my papers collection. They look like this format:

    "citation" : [ 
         "Communications Physics", 
         " 2", 
         "98", 
         "2019"
        ]

I am trying to query all the collection and get the distincts values for position 0 in this array. "Communications Physics" in this case.

db.papers.distinct('citation') doesn't solve my problem, because I only want distincts values for the first element.

I tried distinct formulas of aggregate, but with bad token or incorrect syntax that I can't solve.

Upvotes: 0

Views: 542

Answers (1)

Arsen Davtyan
Arsen Davtyan

Reputation: 1957

If you want to use aggregate:

db.papers.aggregate([
    {$project : {"FirstElement" : { $arrayElemAt: [ "$citation", 0 ] }}}, // Take out the first element from citation array
    {$group : {_id : "$FirstElement"}} // Group By The element you took out
]);

If you want to use distinct try including the index "citation.0":

db.papers.distinct("citation.0");

Upvotes: 2

Related Questions