0

At a certain time interval a IoT device sends data to my backend, I want to keep a document that defines the current state of the device but I also want to see all the other states that the devices has been through.

So I will have State0 - document in my database that contains some information about the device, at State1 I will get some new information that could overwrite the State0 information, but I want to keep track of the changes in the state of the device, so I want to insert a new document that has information merged from State0 and State1 this being the current state of the device.

So my question is: is there a way to easily insert a new document based on information from a previous document? Without finding that document and merging all the fields and after that saving the new document? Does mongo have support for this in any way? Is there another better approach to my problem?

Thanks

exilonX
  • 1,712
  • 3
  • 26
  • 50
  • 2
    Mongodb doesn't support this, you will have to do it programatically. – Kapcash Mar 25 '19 at 11:17
  • 2
    *"Does mongo have support for this in any way?"* - No. Reading a document is not really an atomic process, with the exception of the `findAndModify` variants and that cannot be used to "create a new document based on another" or any part of another. – Neil Lunn Mar 25 '19 at 11:18
  • @NeilLunn I don't see it as a duplicate of that question. It's a little bit different, I want to keep a kind of document version that is just a plain insert of a new field based on other fields – exilonX Mar 25 '19 at 11:21
  • 3
    You cannot read and write at the same time in any way. Pretty much as shown in answers, the only real way to work with "existing data" is to retrieve it via a `findlike` statement, modify it, then do something . Update as specific to the question asked there or "insert" in your case. Small semanctic difference, but not a significant enough difference. It's the same basic question with the same outcome. – Neil Lunn Mar 25 '19 at 11:24

0 Answers0