Getting a list of unique embedded/nested objects in a MongoDB document

前端 未结 4 1403
予麋鹿
予麋鹿 2020-12-16 01:24

Consider the following MongoDB \"recipes\" collection:

{
  \"title\" : \"Macaroni and Cheese\",
  \"ingredients\" : [
    { \"name\" : \"noodles\", \"qty\" :         


        
4条回答
  •  时光说笑
    2020-12-16 01:31

    The following query would give you the bare list minus any duplicates:

    db.recipes.aggregate([{$unwind:"$ingredients"},{$group:{_id:"$ingredients.name"}}])
    

    More work would be necessary to add the quantities. It would be easier if the unit for the quantities was specified separately.

提交回复
热议问题