简体   繁体   中英

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM