Get object at the root level mongodb

486

Use $unwind and $replaceRoot aggregation operators

db.collection.aggregate([   
  { "$unwind": "$sensors" },
  { "$replaceRoot": { "newRoot": { "$mergeObjects": ["$sensors", { "timestamp": "$timestamp" }] }}} 
])
Share:
486
Dmitry  Sokolov
Author by

Dmitry Sokolov

Updated on December 10, 2022

Comments

  • Dmitry  Sokolov
    Dmitry Sokolov over 1 year

    document:

    {"_id":"5cb0dfe234a8a30c9c0af127",
    "sensors":
    [{"value0":0.153,
    "value1":-0.306,
    "value2":9.807}],
    "timestamp":1555095522489,"__v":0}
    

    I want to get 4 field (timestamp and value 0..2) without any array / object. unwind work only against array but not objects. What should I do?

    desired output :

    {timestamp":1555095522489,
    value0":0.153,
    value1":-0.306,
    value2":9.807}
    
    • Ashh
      Ashh about 5 years
      What should be the output?
    • Dmitry  Sokolov
      Dmitry Sokolov about 5 years
      all documents from collection in format : timestamp, value0, value1, value2 {1555095522489, 0.153, -0.306, 9.807}
    • Ashh
      Ashh about 5 years
      Please show the output in JSON format by editing your question
    • krishna Prasad
      krishna Prasad about 5 years