Home > front end >  How to find nested documents mongodb using the official mongo driver
How to find nested documents mongodb using the official mongo driver

Time:01-30

I have this document and would like to filter it to get and document inside the Content array :

[
{
    "ID": "61f1244daeaea5f165851fc9",
    "name": "Mulandi",
    "author": "Owayo",
    "description": "dnjsfnvlksfnvls",
    "created_at": "2022-01-26T10:37:01.558Z",

    "Section": [
        {
            "ID": "61f557213fd9b086c3a422c5",
            "Title": "Weee",
            "Content": [
                {
                    "ID": "61f5586e3fd9b086c3a422dc",
                    "Subsection_Title": "Idk",
                    "Content": "Something"
                }
            ]
        }
    ],
}

]

how should i go about so as to filter this document i tried this but it didn't work :

pipeline := []bson.M{
        {"$match": bson.M{"Name": name}},
        {"$unwind": "$Section"},
        {"$unwind": "$Section.Content"},
        {"$project": bson.M{
            "Section.Title":                sectiontitle,
            "Section.Content.subsectionid": iuud,
        }},
    }
    iter, err := collection.Aggregate(ctx, pipeline)
    if err != nil {
        return nil, err
    }
    var elem models.Course
    for iter.Next(ctx) {
        var elem models.Section
        err = iter.Decode(&elem)
        if err != nil {
            log.Fatal(err)
        }
    }

CodePudding user response:

db.collection.aggregate([
  {
    "$match": {
      "name": "Mulandi"
    }
  },
  {
    "$unwind": "$Section"
  },
  {
    "$unwind": "$Section.Content"
  },
  {
    "$match": {
      "Section.Content.ID": "61f5586e3fd9b086c3a422dc"
    }
  },
  {
    "$project": {
      "Subsection_Title": "$Section.Content.Subsection_Title",
      "Content": "$Section.Content.Content",
      "_id": "$Section.Content.ID"
    }
  }
])

mongoplayground

CodePudding user response:

iuud, _ := primitive.ObjectIDFromHex(subsectionid)
pipeline := []bson.M{
    {"$match": bson.M{"Name": name}},
    {"$unwind": "$Section"},
    {"$unwind": "$Section.Content"},
    {"$match": bson.M{"Section.Content.ID": iuud}},
    {"$project": bson.M{
        "Subsection_Title": "$Section.Content.Subsection_Title",
        "Content":       "$Section.Content.Content",
    }},
} 
iter, err := collection.Aggregate(ctx, pipeline)
if err != nil {
    return nil, err
}
var results []bson.M
if err = iter.All(context.TODO(), &results); err != nil {
    log.Fatal(err)
}

This helped me finding the nested documents Thanks @YuTing ,but It seems in Pipeline it doesn't return the id of the subdocument instead it returns the id of the document i.e "61f1244daeaea5f165851fc9" instead of : "61f5586e3fd9b086c3a422dc" how can I change this ?

  •  Tags:  
  • Related