I have a collection of documents by type:

{fields:{_id:1, f1:10, f2:"репа", f3:200}, computedFields:{id:1}}, {fields:{_id:2, f1:10, f2:"репа", f3:200}, computedFields:{id:2}}, ... 

Inside the cursor (pipeline) I need to convert each document to the form:

 {_id:1, f1:10, f2:"репа", f3:200, id:1}, {_id:2, f1:10, f2:"репа", f3:200, id:2}, ... 

Those. need to get rid of the top level, leaving the bottom

Please tell me how to do it.

  • If you do not want to change the structure of the documents, then you need to use mapReduce because you do not know the name of all the fields. - styvane

2 answers 2

Since fields have their own unique identifiers, you can use the distinct method:

 SomeModel.distinct("fields") 

This code will return a list of unique fields objects from all objects of the SomeModel collection. If you need results with repetitions, then distinct will not help here.

    try this:

     db.collection.aggregate([ { $addFields: { array: { $concatArrays: [ { $objectToArray: "$fields" }, { $objectToArray: "$computedFields" } ] } } }, { $replaceRoot: { newRoot: { $arrayToObject: "$array" } } } ]) 
    • I'm sorry должен I have to work now - jaksz