1

I have a mongodb collection and each document in that collection contains an array of a different document type.

EX:

{
   _Id: SomeObjectID,
    AnArray:[
               { value:"SomeValue1", Id:1},
               { value:"SomeValue2", Id:2},
               { value:"SomeValue3", Id:3},
            ]
},
{
    _Id: AnotherObjectID,
    AnArray:[
               { value:"SomeValue1", Id:1},
               { value:"SomeValue4", Id:4},                  
               { value:"SomeValue5", Id:5},
            ]
}

If you see the above collection and first element of the AnArray field, you will see that element index 1 in the array of both the documents have the same value: SomeValue1, ID: 1.

What I want to do is, fetch all the distinct values from the first element of the array of all documents.

I have no clue on how to do this and not sure what to ask Google, so I am adding this as a question here.

I am using mongoose with mongodb and did not find any methods that would help me do that.

Really appreciate any help.

1 Answer 1

2

You can use mongo aggregation pipeline to get your results.

$arrayElemAt can be use to get the nth element from an array.

Aggregation query:

db.sample.aggregate([
    {$project : {arr_0_value : {$arrayElemAt : ['$AnArray',0]}}},
    {$project : {arr_value:'$arr_0_value.value'}},
    {$group : {_id:'$arr_value'}}
])

Output:

{ "_id" : "SomeValue1" }
{ "_id" : "SomeValue5" }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.