'Updating specific record using Update.Set & Update.Push in nested collections in MongoDB
I have the following entities:
public class Profile
{
public Guid Id {get; private set;}
public ICollection<User> Users {get; protected set;}
}
public class User
{
public Guid Id {get; private set;}
public ICollection<Address> Addresses {get; protected set;}
}
public class Address
{
public Guid Id {get; private set;}
public string AddressProperty Address {get;set;}
}
We have a parent collection called Profiles and other classes are nested inside this document.
Let's take a look at the levels of nested collection:
One Profile can have -> multiple Users where each user can have -> multiple addresses
Now let's look at Update code for User collection:
public async Task<bool> UpdateUser(Guid profileId, User userData)
{
var dbContext = await GetDbContextAsync();
var collection = dbContext.Collection<Profile>();
var record = await collection.UpdateOneAsync(
Builders<Profile>.Filter.Eq(rec => rec.Id, profileId),
Builders<Profile>.Update.Set(x => x.Users.ElementAt(-1), userData)
);
return record.IsAcknowledged;
}
The above code works fine.
Where I am stuck at is while trying to update Address inside a User using a separate operation like UpdateAddress
to which we pass the UserId.
How do we write Update.Set
for a collection (Addresses) which is inside a collection (Users) inside another one (Profiles) where Profiles is the parent document?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|