문제

In MongoDB I have an update query that works:

db.posts.update(
  { 
    "_id" : ObjectId("..."),
    "Comments.Reference" : 123 
  },
  { 
    $push : 
    { 
      "Comments.$.Notes": { Text: "Some description here" } 
    }
  });

This finds the Post document with the matching Id, and to the Comments object with the matching reference in that array, it will push a new object into the Notes array within it.

However, as I am using C# and the driver, I wanted to see if it was possible to create this with LINQ.

Where I am falling down is creating an update query that translates to creating the $ positional operator.

IMongoUpdate update = Update<Post>.Push(t => t.Comments.First().Notes,
                                        BsonDocument.Parse("{ Text: \"Test\"}");

I put the First() as a first guess and to get it to compile, however it throws an error to say that it can't serialize it.

Is it possible to recreate this, or will I just have to revert to using a string query of "Comments.$.Notes" instead?

Edit: Just to update, this is what works, but provides no type safety:

IMongoUpdate update = Update.Push("Comments.$.Notes",
                                  BsonDocument.Parse("{ Text: \"Test\"}");
도움이 되었습니까?

해결책

This functionality has been added:

https://jira.mongodb.org/browse/CSHARP-1046

To copy directly from the jira case:

Builders<Entity>.Update.Set(x => x.MyArray[-1].Value, 10);

will yield

{ $set: { "MyArray.$.Value", 10 } }

다른 팁

Unfortunately it looks like it is not supported at this time :(

https://jira.mongodb.org/browse/CSHARP-531

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top