Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch distinct values from Mongo DB nested array and output to a single array

given below is my data in mongo db.I want to fetch all the unique ids from the field articles ,which is nested under the jnlc_subjects index .The result should contain only the articles array with distinct object Ids.

Mongo Data

{
"_id" : ObjectId("5c9216f1a21a4a31e0c7fa56"),
"jnlc_journal_category" : "Biology",
"jnlc_subjects" : [ 
    {
        "subject" : "Conservation Biology",
        "views" : "123",
        "articles" : [ 
            ObjectId("5c4e93d0135edb6812200d5f"), 
            ObjectId("5c4e9365135edb6a12200d60"), 
            ObjectId("5c4e93a8135edb6912200d61")
        ]
    }, 
    {
        "subject" : "Micro Biology",
        "views" : "20",
        "articles" : [ 
            ObjectId("5c4e9365135edb6a12200d60"), 
            ObjectId("5c4e93d0135edb6812200d5f"), 
            ObjectId("5c76323fbaaccf5e0bae7600"), 
            ObjectId("5ca33ce19d677bf780fc4995")
        ]
    }, 
    {
        "subject" : "Marine Biology",
        "views" : "8",
        "articles" : [ 
            ObjectId("5c4e93d0135edb6812200d5f")
        ]
    }
]
}

Required result
I want to get output in following format

articles : [ 
            ObjectId("5c4e9365135edb6a12200d60"), 
            ObjectId("5c4e93a8135edb6912200d61"),
            ObjectId("5c76323fbaaccf5e0bae7600"), 
            ObjectId("5ca33ce19d677bf780fc4995"),
            ObjectId("5c4e93d0135edb6812200d5f")
        ]
like image 588
Vishnudas Avatar asked Jun 25 '26 03:06

Vishnudas


2 Answers

Try as below:

db.collection.aggregate([
        {
            $unwind: "$jnlc_subjects"
        },
        {
            $unwind: "$jnlc_subjects.articles"
        },
        { $group: {_id: null, uniqueValues: { $addToSet: "$jnlc_subjects.articles"}} }
    ])

Result:

{
    "_id" : null,
    "uniqueValues" : [
        ObjectId("5ca33ce19d677bf780fc4995"),
        ObjectId("5c4e9365135edb6a12200d60"),
        ObjectId("5c4e93a8135edb6912200d61"),
        ObjectId("5c4e93d0135edb6812200d5f"),
        ObjectId("5c76323fbaaccf5e0bae7600")
    ]
}
like image 81
Jitendra Avatar answered Jun 27 '26 16:06

Jitendra


Try with this

db.collection.aggregate([
{
$unwind:{
 path:"$jnlc_subjects",
 preserveNullAndEmptyArrays:true
 }   
},
{
$unwind:{
 path:"$jnlc_subjects.articles",
 preserveNullAndEmptyArrays:true
 }   
},
{
$group:{
    _id:"$_id",
    articles:{
        $addToSet:"$jnlc_subjects.articles"
        }
    }
}
])

If you don't want to $group with _id ypu can use null instead of $_id

like image 38
Ashwanth Madhav Avatar answered Jun 27 '26 15:06

Ashwanth Madhav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!