Nilesh
Nilesh

Reputation: 2691

Get nested document based on array index

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.

Upvotes: 1

Views: 359

Answers (1)

4J41
4J41

Reputation: 5095

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" }

Upvotes: 2

Related Questions