0

I'm building an statistical system that when an user clicks a link, the python server sends date and time data to MongoDB. For example, if now is "2020-11-10, 11:41:20" then in MongoDB, there should be

{
  _id: "1123",
  time: {
    2020: {
      11: {
        10: ["11:41:20"]
      }
    }
  }
}

then, if another user clicks the link, say the time is "2020-11-13, 10:23:00", I want to push the data into already existing document above. The result should be

{
  _id: "1123",
  time: {
    2020: {
      11: {
        10: ["11:41:20"],
        13: ["10:23:00"]
      }
    }
  }
}

What I've been doing is get all the data into a python object and manually insert new time data to the object, and update the whole document. is there any neat way to implement this?

Thanks in advance.

1
  • 1
    I don't think it is a smart design to use dynamic field names. You would need to use again and again $objectToArray, $arrayToObject and $reduce operators. Apart from that you should never store date/time values as string, use proper Date objects. Commented Nov 10, 2020 at 9:22

1 Answer 1

1

Just use dot notation with $push operator, if the parent object not existing, the mongodb will create automatically.

> db.test.findOne()
{
  "_id" : "1123",
  "time" : {
    "2020" : {
      "11" : {
        "10" : [
          "11:41:20"
        ],
        "13" : [
          "10:23:00"
        ]
      }
    }
  }
}
> db.test.updateOne({_id: '1123'}, {
  $push: {
    'time.2020.11.14': '23:00:00',
    'time.2020.11.13': '23:01:00'
  }
})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.test.findOne()
{
  "_id" : "1123",
  "time" : {
    "2020" : {
      "11" : {
        "10" : [
          "11:41:20"
        ],
        "13" : [
          "10:23:00",
          "23:01:00"
        ],
        "14" : [
          "23:00:00"
        ]
      }
    }
  }
}

https://docs.mongodb.com/manual/core/document/#dot-notation https://docs.mongodb.com/manual/reference/operator/update/push/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.