Simple update which inserts

Hi Guys,

I want to save gps positions of a driven route. So want to create a collection which stores:

user-id, route-id, [positions]

The positions should be a list of values:

date,lat,long

I found out, I can $push into array fields to add information: https://docs.mongodb.com/manual/reference/operator/update/push/

So everytime when I get a new route coordinate, I would do:

db.students.update(
   { user-id: 2323, route-id: 0 },
   { $push: { positons: {date: 123, lat: 123, long: 123} } }
)

But what I need to do at the first insertion? When there isn’t a entry in the database, where I can do a $push ?

Can I just set upsert to true ? But would this query insert the array and the user-id and the route-id ?

T

You could do an insert or an insertOne.
db.students.insertOne({“user-id”: 2323, “route-id”: 0, “positions”: {“date”:123, “lat”: 123, “long”: 123}}). Which would give you the follow document in your DB.
image

Then if you needed to update you could use the $push you showed above.

Also, mongodb has information on geoJson, which can allow you to use $geonear in an aggregation pipeline and some other features as well. https://docs.mongodb.com/manual/geospatial-queries/#geospatial-geojson

I had a typo in my insert query it should be:
db.students.insertOne({“user-id”: 2323, “route-id”: 0, “positions”: [{“date”:123, “lat”: 123, “long”: 123}]}).

Here is the update, and the modified document: