I have the following document
in a collection called Users
in MongoDB. I am trying to insert a <SpecificBeer>
into beersInCellar[]
of the mycellar
cellar
. I've tried all kinds of combinations in the filter
and update
objects but just can't wrap my head around inserting into a nested array. I know how to find
a document
and insert things into it, just not into an array in that document.
{
"_id" : ObjectId("5920751b6d4f6a27cf7985a8"),
"name" : "FullName",
"emailAddress" : "emailaddress@example.com",
"cellars" : [
{
"cellarId" : "mycellar",
"cellarName" : "My Cellar",
"beersInCellar" : [ ]
}
]
}
SpecificBeer model:
public class SpecificBeer
{
public string ourid
{
get
{
return ID.ToString();
}
set
{
ID = ObjectId.Parse(value);
}
}
[BsonId]
private ObjectId ID {get; set;}
public string year { get; set; }
public string variant { get; set; }
public string quantity { get; set; }
public string numberForTrade { get; set; }
}
Insert method
public async Task<SpecificBeer> AddBeerToList(string id, SpecificBeer specificBeer, string cellarId)
{
var filter = Builders<User>.Filter.Eq(e => e.userId, id) & Builders<User>.Filter.Eq(e => e.cellars, cellarId);
var update = Builders<Cellar>.Update.Push<SpecificBeer>(e => e.beersInCellar, specificBeer);
await _collection.FindOneAndUpdateAsync(filter, update);
return specificBeer;
}