MongoDb C# Driver - Setting server timestamp on a upsert

431 views
Skip to first unread message

Boas Enkler

unread,
Sep 5, 2017, 10:44:37 AM9/5/17
to mongodb-user

I ve a mongodb server with version 3.0.0.

I want to get a BsonTimespan field created by the server. In the current case i'm doing an upsert.

But currently it only gets an empty value or 1970-01-01T00:00:00.000Z (#0).


As it is a server version auf 3.0.0 it shouldn't be at first position right?



What am I doing wrong?


Dto

    [BsonIgnoreExtraElements]

    public sealed class EventCommit

    {

        [BsonId]

        public ObjectId Id { get; set; }



        [BsonRequired]

        [BsonElement("atp")]

        public string AggregatePackage { get; set; }


        [BsonRequired]

        [BsonElement("atys")]

        public string AggregateTypeShort { get; set; }


        [BsonRequired]

        [BsonElement("ord")]

        public long Ordinal { get; set; }


        [BsonRequired]

        [BsonElement("tst")]

        [BsonDateTimeOptions(Kind = DateTimeKind.Utc)]

        public DateTime Timestamp { get; set; }


        [BsonRequired]

        [BsonElement("stst")]

        public BsonTimestamp ServerTimestamp { get; set; }


        [BsonRequired]

        [BsonElement("v")]

        public long Version { get; set; }


        [BsonRequired]

        [BsonElement("eve")]

        public Dictionary<string, EventDto> Events { get; set; }

    }

}

and this is the UpdateDefinition

 UpdateDefinition<EventCommit> update = Updates

                .SetOnInsert(x => x.Ordinal, ordinal)

                .SetOnInsert(x => x.Timestamp, commit.Timestamp)

                .SetOnInsert(x => x.Version, commit.Version)

                .SetOnInsert(x => x.AggregatePackage, commit.AggregatePackage)

                .SetOnInsert(x => x.ServerTimestamp,new BsonTimestamp(0))



Wan Bachtiar

unread,
Oct 11, 2017, 12:50:16 AM10/11/17
to mongodb-user

Hi Boas,

You could also utilise $currentDate update operator and perform upsert :
For example using MongoDB .NET driver v2.3.x:

var query = new BsonDocument(); 
var update = Builders<BsonDocument>.Update.CurrentDate("lastModified");
var updateOptions = new UpdateOptions {IsUpsert = true};

var result = collection.UpdateOne(query, update, updateOptions);

Regards,
Wan.

Reply all
Reply to author
Forward
0 new messages