MongoDb c# 2.0 driver AddToSet method - c#

I have the following code which was implemeted with MongoDb 2.0 c# driver. But I need to access to the MailLists collection of Profile which will be inserted. I've written the expected solution using p in constructor, but how to implement it via multiple operation?
IMongoCollection<Profile> dbCollection = DetermineCollectionName<Profile>();
var filter = Builders<Profile>.Filter.In(x => x.ID, profiles.Select(x => x.ID));
var updateMl = Builders<Profile>.Update.AddToSet(p => p.MailLists, new Profile2MailList
{
MailListId = maillistId,
Status = p.MailLists.MergeMailListStatuses(),
SubscriptionDate = DateTime.UtcNow
});
dbCollection.UpdateManyAsync(filter, updateMl, new UpdateOptions { IsUpsert = true });

I found the following solution:
IMongoCollection<Profile> dbCollection = DetermineCollectionName<Profile>();
var filter = Builders<Profile>.Filter.In(x => x.ID, profiles.Select(x => x.ID));
var profile2maillists = new List<Profile2MailList>();
foreach(var profile in profiles)
{
profile2maillists.Add(
new Profile2MailList
{
MailListId = maillistId,
Status = profile.MailLists.MergeMailListStatuses(),
SubscriptionDate = DateTime.UtcNow
});
}
var updateMl = Builders<Profile>.Update.AddToSetEach(p => p.MailLists, profile2maillists);
dbCollection.UpdateManyAsync(filter, updateMl, new UpdateOptions { IsUpsert = true });

Related

Entity Framework Include performance problems

Good Morning,
I have a problem with the performance if i use include.
Have a look at the following query, if I load the data from the include (x.Server_Item.itemType) the query needs like 980ms.
If i remove them, the query needs 51ms.
980ms:
using (var db = new dbContext())
{
var items = db.Characters_Inventory
.Where(x => x.charId == charId && x.itemLocation == ItemLocationInventory)
.Include(p => p.Server_Items)
.AsSplitQuery()
.Select(x => new
{
itemId = x.id,
x.itemName,
x.nameTag,
x.itemAmount,
x.itemLocation,
x.isItemEquipped,
x.itemCategory,
x.metaId,
x.metaTag0,
x.metaTag1,
itemType = x.Server_Items.itemType,
itemSubType = x.Server_Items.itemSubType,
itemClothesType = x.Server_Items.Server_Clothes.type,
itemPicName = x.Server_Items.itemPicSRC,
itemWeight = x.Server_Items.itemWeight,
itemGender = x.Server_Items.Server_Clothes.gender,
isItemUseable = x.Server_Items.isItemUseable,
isItemDroppable = x.Server_Items.isItemDroppable,
isItemGiveable = x.Server_Items.isItemGiveable,
isItemStorable = x.Server_Items.isItemStorable,
isItemStackable = x.Server_Items.isItemStackable,
isItemShowable = x.Server_Items.isItemShowable,
isItemNameable = x.Server_Items.isItemNameable,
isItemPlaceable = x.Server_Items.isItemPlaceable,
//isClothesTypeEquipped = IsClothesTypeEquipped(charId, x.id),
isClothesSwitchable = x.Server_Items.Server_Clothes.altClothesName != "" ? true : false
//isWeaponTypeEquipped = IsWeaponTypeEquipped(charId, x.id),
//charName = Characters.GetCharacterName(x.metaId)
}).AsNoTracking().ToList();
return JsonConvert.SerializeObject(items);
}
50ms:
using (var db = new dbContext())
{
var items = db.Characters_Inventory
.Where(x => x.charId == charId && x.itemLocation == ItemLocationInventory)
.Include(p => p.Server_Items)
.AsSplitQuery()
.Select(x => new
{
itemId = x.id,
x.itemName,
x.nameTag,
x.itemAmount,
x.itemLocation,
x.isItemEquipped,
x.itemCategory,
x.metaId,
x.metaTag0,
x.metaTag1
}).AsNoTracking().ToList();
return JsonConvert.SerializeObject(items);
}
I tried with AsSplitQuery and without AsSplitQuery.
Maybe nice to know: On the included table (Server_Items) is alrdy a table included.
Thanks in advance.
Sincerely

MongoDB Update nested Array object where there is a match in array document

Here is my MongoDB Document
{
"_id":20,
"GroupId":"45",
"Name":"Some Name",
"NestedArray":[
{
"Id":3,
"Name":"NesName",
"IsDeleted":false
}
]
}
I need to write a update statement like (in SQL interpretation)
update MyCollections.NestedArray set MyCollections.NestedArray[x].IsDeleted = true where MyCollections.NestedArray[x].Id = 3
Here is what I tried
var groupFilter = Builders<MyType>.Filter.Eq(x => x.Id, 45);
var nestedArayDocUpdate = Builders<MyType>.Update.Set(x => x.NestedArray[0].IsDeleted, true);
mongoDbRepository.UpdateMany(groupFilter, nestedArayDocUpdate,
new UpdateOptions {IsUpsert = false, BypassDocumentValidation = false});
using MongoDB 3.2 how can I come up with a MongoDB C# driver query?
This is how I ended up doing it.
var updateBuilder = Builders<Type>.Update.
.Set(x => x.NestedArray[-1].IsActive, false)
.Set(x => x.NestedArray[-1].IsDeleted, true);
mongoDbRepository.UpdateOne( Builders<Type>.Filter.Where(
x => x.NestedArray.Any(c => c.Id == categoryId)), updateBuilder);

LINQ to Entities does not recognize the method String.Format

I'm trying to format a double value (by showing only 2 decimals). I tried to use AsEnumerable but I keep getting this error
LINQ to Entities does not recognize the method
String.Format
var tw = workers.Select(x => new
{
Id = x.Id,
JobOpportunityFeedbacks = x.JobOpportunityFeedbacks.AsEnumerable().
Select(y => new
{
Rating = String.Format("0.00",y.Rating),
Feedback = y.Feedback
});
You have to do the AsEnumerable outside of your initial Select
var tw = workers.Select(x => new
{
Id = x.Id,
JobOpportunityFeedbacks = x.JobOpportunityFeedbacks
.Select(y => new
{
y.Rating,
y.Feedback
})
})
.AsEnumerable()
.Select(x => new
{
x.Id,
JopOpertunityFeedbacks = x.JobOpportunityFeedbacks
.Select(y => new
{
Rating = String.Format("0.00",y.Rating),
y.Feedback
})
});
Use SqlFunctions class - I didn't try this but should work.
var tw = workers.Select(x => new
{
Id = x.Id,
JobOpportunityFeedbacks = x.JobOpportunityFeedbacks.AsEnumerable().
Select(y => new
{
Rating = SqlFunctions.StringConvert(y.Rating, 4, 2)
Feedback = y.Feedback
});
https://msdn.microsoft.com/en-us/library/dd487158(v=vs.110).aspx

MongoDB Map Property 'new' in findAndModify using FindOneAndUpdateOptions class C# Driver

I'm trying to implement a getNextSequence function for mongoDB explain on this Link I'm using the lattes C# driver but I not sure how to map the new : true property in the FindOneAndUpdateOptions
MongoDB Code
function getNextSequence(name) {
var ret = db.counters.findAndModify(
{
query: { _id: name },
update: { $inc: { seq: 1 } },
new: true,
upsert: true
}
);
return ret.seq;
}
C# Code
public async Task<long> GetNextObjectSequenceAsync(string objectName)
{
var collection = this.Context.GetCollection<ObjectSequence>("Counters");
var filter = new FilterDefinitionBuilder<ObjectSequence>().Where(x => x.Name == objectName);
var options = new FindOneAndUpdateOptions<ObjectSequence, ObjectSequence>() { IsUpsert = true };
var update = new UpdateDefinitionBuilder<ObjectSequence>().Inc(x => x.Sequence, 1);
ObjectSequence seq = await collection.FindOneAndUpdateAsync<ObjectSequence>(filter, update, options);
return seq.Sequence;
}
FindOneAndUpdateOptions has ReturnDocument enum where
ReturnDocument.Before = 'new':false
ReturnDocument.After = 'new':true
In your case options should be:
var options = new FindOneAndUpdateOptions<ObjectSequence, ObjectSequence>() { ReturnDocument = ReturnDocument.After, IsUpsert = true };

Elasticsearch.NET NEST Object Initializer syntax for a highlight request

I've got:
var result = _client.Search<ElasticFilm>(new SearchRequest("blaindex", "blatype")
{
From = 0,
Size = 100,
Query = titleQuery || pdfQuery,
Source = new SourceFilter
{
Include = new []
{
Property.Path<ElasticFilm>(p => p.Url),
Property.Path<ElasticFilm>(p => p.Title),
Property.Path<ElasticFilm>(p => p.Language),
Property.Path<ElasticFilm>(p => p.Details),
Property.Path<ElasticFilm>(p => p.Id)
}
},
Timeout = "20000"
});
And I'm trying to add a highlighter filter but I'm not that familiar with the Object Initializer (OIS) C# syntax. I've checked NEST official pages and SO but can't seem to return any results for specifically the (OIS).
I can see the Highlight property in the Nest.SearchRequest class but I'm not experienced enough (I guess) to simply construct what I need from there - some examples and explanations as to how to employ a highlighter with OIS would be hot!
This is the fluent syntax:
var response= client.Search<Document>(s => s
.Query(q => q.Match(m => m.OnField(f => f.Name).Query("test")))
.Highlight(h => h.OnFields(fields => fields.OnField(f => f.Name).PreTags("<tag>").PostTags("</tag>"))));
and this is by object initialization:
var searchRequest = new SearchRequest
{
Query = new QueryContainer(new MatchQuery{Field = Property.Path<Document>(p => p.Name), Query = "test"}),
Highlight = new HighlightRequest
{
Fields = new FluentDictionary<PropertyPathMarker, IHighlightField>
{
{
Property.Path<Document>(p => p.Name),
new HighlightField {PreTags = new List<string> {"<tag>"}, PostTags = new List<string> {"</tag>"}}
}
}
}
};
var searchResponse = client.Search<Document>(searchRequest);
UPDATE
NEST 7.x syntax:
var searchQuery = new SearchRequest
{
Highlight = new Highlight
{
Fields = new FluentDictionary<Field, IHighlightField>()
.Add(Nest.Infer.Field<Document>(d => d.Name),
new HighlightField {PreTags = new[] {"<tag>"}, PostTags = new[] {"<tag>"}})
}
};
My document class:
public class Document
{
public int Id { get; set; }
public string Name { get; set; }
}

Categories

Resources