简体   繁体   中英

Is there a way to retrivere data from mongodb as key-value map where keys are values of a field (using Mongoose)

I have these data in my Mongodb collection:

{_id: xxx1, fieldA: valueA_1, fieldB: valueB_1, fieldC: valueC_1},
{_id: xxx2, fieldA: valueA_1, fieldB: valueB_2, fieldC: valueC_2},
{_id: xxx3, fieldA: valueA_2, fieldB: valueB_3, fieldC: valueC_3},

Is there a Mongodb aggregate operator or such that would return this kind of structure:

{
 "valueA_1": [
              {_id: xxx1, fieldA: valueA_1, fieldB: valueB_1, fieldC: valueC_1},
              {_id: xxx2, fieldA: valueA_1, fieldB: valueB_2, fieldC: valueC_2}
             ],

 "valueA_2": [
              {_id: xxx3, fieldA: valueA_2, fieldB: valueB_3, fieldC: valueC_3}
             ]
}

Right now I am doing a simple Schema.find() and after that I apply a reduce function to the result:

    data.reduce(function (map, obj) {
      map[obj.fieldA] = map[obj.fieldA] ? [...map[obj.fieldA], obj] : [obj];
      return map;
    }, {});

I would like to know how can I accomplish this behavior using mongodb\mongoose operators only and also if performances would be better using them instead of the reduce function

Thank you all!

try this

db.collection.aggregate([
  {
    $group: { // first group by the required fieldA
      _id: "$fieldA",
      docs: {
        $push: "$$ROOT"
      }
    }
  },
  {
    $group: { // this group to gather all documents in one array 'allDocsInOneArray' of objects
      // each object has a key = the value of fieldA, and a value = an array of the docs belong to this fieldA
      _id: null,
      allDocsInOneArray: {
        $push: {
          k: "$_id", // the key of the object (should be the value of fieldA, which is the _id now after the first group stage)
          v: "$docs" // an array of docs belong to this fieldA
          // the object should be in this format { k: '', v: [] } in order to be able to convert the whole array to another object in $arrayToObject operation
        }
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": {
        "$arrayToObject": "$allDocsInOneArray"  // convert the array of objects to object with key = k (fieldA), value = v (its docs)
      }
    }
  }
])

you can test it here

hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM