private void AddUserFavoriteMovie( User user, Movie favoriteMovie, MongoCollection<User> userCollection ) { var movieShort = new MovieShortDetail( favoriteMovie ); var movieShortBson = movieShort.ToBsonDocument(); // Add permanently to model without saving user.FavoriteMovies.Add( movieShort ); // Add atomically to database userCollection.Update( Query.EQ( IdFieldName, user.Id ), Update.AddToSet( FavoriteMoviesFieldName, movieShortBson ) ); // Update favorite movie collections for user's friends var friendIds = user.Friends.Select( f => f.UserId ).ToArray(); var friends = userCollection.AsQueryable().Where( u => friendIds.Contains( u.Id ) ); foreach (var friend in friends) { userCollection.Update( Query.EQ( IdFieldName, friend.Id ), Update.AddToSet( FriendsFavoriteMoviesFieldName, movieShortBson ) ); } }
private void MakeFriends( User first, User second, MongoCollection userCollection ) { var firstFriend = new Friend( first ); var secondFriend = new Friend( second ); // Add permanently to model without saving first.Friends.Add( secondFriend ); second.Friends.Add( firstFriend ); // Add atomically to database userCollection.Update( Query.EQ( IdFieldName, first.Id ), Update.AddToSet( FriendsFieldName, secondFriend.ToBsonDocument() ) ); userCollection.Update( Query.EQ( IdFieldName, second.Id ), Update.AddToSet( FriendsFieldName, firstFriend.ToBsonDocument() ) ); // Update favorite movie collections for two users userCollection.Update( Query.EQ( IdFieldName, first.Id ), Update.AddToSetEachWrapped( FriendsFavoriteMoviesFieldName, (IEnumerable<MovieShortDetail>)second.FavoriteMovies ) ); /* We need this explicit type cast because driver * wrong interpret ICollection and added whole * collection as one element. */ userCollection.Update( Query.EQ( IdFieldName, second.Id ), Update.AddToSetEachWrapped( FriendsFavoriteMoviesFieldName, (IEnumerable<MovieShortDetail>)first.FavoriteMovies ) ); }
public IEnumerable<MovieShortDetail> GetFriendsFavotiteMovies( User user ) { var userCollection = _dataBase.GetCollection( UserCollectionName ); var friendIds = user.Friends.Select( u => (BsonValue)u.UserId ); IMongoQuery selectQuery = Query.In( IdFieldName, friendIds ); var result = userCollection.Distinct( FavoriteMoviesFieldName, selectQuery ) .Select(doc => BsonSerializer.Deserialize<MovieShortDetail>((BsonDocument) doc)); return result; }