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

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

Consider the following MongoDB \"recipes\" collection:

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


        
4条回答
  •  误落风尘
    2020-12-16 01:50

    A funny way of doing it in the mongoshell using foreach operator

    var list = [];
    db.recepies.find(
      {},
      {'ingredients.name' : 1, _id : 0}
    ).forEach(function(doc){
      var ingredients = doc.ingredients;
      for (var i=0; i< ingredients.length; i++){
        var ingredient = ingredients[i].name;
        if (list.indexOf(ingredient) == -1){
           list.push(ingredient)
        }
      }
    });
    

    after this list will contain all the elements. P.S. I am sure this is also possible with aggregation framework.

提交回复
热议问题