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:


I found out, I can $push into array fields to add information:

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

   { 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 ?


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.

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.

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: