I'm new to C# mongo,earlier worked on Node and Mongo.
i have a collection called tasks.Below is a sample record.
{
"_id" : ObjectId("6193bfba23855443a127466a"),
"taskIdentifier" : LUUID("00000000-0000-0000-0000-000000000000"),
"title" : "PR Liquidators",
"company" : "iuytreugdfh",
"purpose" : "test purpose",
"column" : "Search",
"assignTo" : "Shiva",
"assignToId" : ObjectId("61933b47a79ac615648a7855"),
"assignToImage" : null,
"notes" : "ggh#William james ",
"done" : 0,
"taskID" : "00029",
"status" : "Pending",
"states" : [
"Alabama - AL",
"Alaska - AK"
],
"active" : true,
"updatedAtUtc" : ISODate("2021-11-18T12:26:37.616Z"),
"updatedBy" : ""
}
in my c# webapi Project i always get a array called filterCriteria from api request of below form:
filterCriteria=[
{key:"purpose",value:"test purpose",type:"eq"},
{key:"active",value:true,type:"eq"}
]
Now I want to query the mongo collection tasks using the given filterCriteria.
tried something using LINQ statements but no use --hardcoding works but dynamically not working.
How can I achieve this???
maybe you are looking for Builders:
public enum FilterType{
eq=1,//equal
gt=2//greater than
}
//************
var builder = Builders<FilterCritertiaModel>.Filter;
var query = builder.Empty;
foreach(var filterCriteriaItem in filterCriteria){
switch (filterCriteriaItem.type) {
case eq:
query &= builder.Eq(filterCriteriaItem.Key, filterCriteriaItem.Value);
case gt:
query &=builder.Gt(filterCriteriaItem.Key, filterCriteriaItem.Value);
//all cases....
}
Related
I use firebase.database to make query from Firebase in c#, i want to make like Where in linq But i didn't find any extension method that would help.
I have CallHistory table has many properties like Rate,Id,Status and
make index in Rate property this is json of callhistory
"CallHistory" : {
"0798af9c-180c-4d67-a58d-a47043f7e36f" : {
"CreatedDate" : "0001-01-01T00:00:00Z",
"Id" : "0798af9c-180c-4d67-a58d-a47043f7e36f",
"IsActive" : false,
"IsDeleted" : false,
"Latitude" : 1.5,
"ModifiedDate" : "0001-01-01T00:00:00Z",
"Rate" : 5,
"RecipientId" : "00000000-0000-0000-0000-000000000000",
"Status" : 2,
"StatusDateTime" : "0001-01-01T00:00:00Z",
"longitude" : 1.2
},
"151c7072-0b17-44aa-a834-99c265ef897f" : {
"CreatedDate" : "0001-01-01T00:00:00Z",
"Id" : "151c7072-0b17-44aa-a834-99c265ef897f",
"IsActive" : false,
"IsDeleted" : false,
"Latitude" : 1.5,
"ModifiedDate" : "0001-01-01T00:00:00Z",
"Rate" : 4,
"RecipientId" : "00000000-0000-0000-0000-000000000000",
"Status" : 1,
"StatusDateTime" : "0001-01-01T00:00:00Z",
"longitude" : 1.2
}
}
and write this code
using Firebase.Database;
using Firebase.Database.Query;
var firebase = new FirebaseClient("https://sound-project-42ead.firebaseio.com/");
var calls = await firebase
.Child("CallHistory").OrderBy("Rate").EqualTo("4")
.OnceAsync<CallHistory>();
But it doesn;t return any data.
With search i found that there are function called OrderByChild() , But i did'nt find this method anymore
in firebase.database.query.
Is There any other dll can i install it to find orderbychild().
Firebase Realtime Database queries compare the actual type of the stored data and of the value you specify. And the string "4" is not the same as a numerical value 4.
So you'll want to pass a number:
var firebase = new FirebaseClient("https://sound-project-42ead.firebaseio.com/");
var calls = await firebase
.Child("CallHistory").OrderBy("Rate").EqualTo(4)
...
Let's say we have a collection of documents like this one:
{
"_id" : ObjectId("591c54faf1c1f419a830b9cf"),
"fingerprint" : "3121733676",
"screewidth" : "1920",
"carts" : [
{
"cartid" : 391796,
"status" : "New",
"cart_created" : ISODate("2017-05-17T13:50:37.388Z"),
"closed" : false,
"items" : [
{
"brandid" : "PIR",
"cai" : "2259700"
}
],
"updatedon" : ISODate("2017-05-17T13:51:24.252Z")
},
{
"cartid" : 422907,
"status" : "New",
"cart_created" : ISODate("2017-10-23T08:57:06.846Z"),
"closed" : false,
"items" : [
{
"brandid" : "PIR",
"cai" : "IrHlNdGtLfBoTlKsJaRySnM195U"
}
],
"updatedon" : ISODate("2017-10-23T09:46:08.579Z")
}
],
"createdon" : ISODate("2016-11-08T10:29:55.120Z"),
"updatedon" : ISODate("2017-10-23T09:46:29.486Z")
}
How do you extract only the documents where no item in the array $.carts have $.carts.closed set to true and $.carts.updatedon greater than $.updatedon minus 3 days ?
I know how to do find all the documents where no item in the array satisfy the condition $and: [closed: {$eq: true}, {updatedon: {$gt : new ISODate("2017-10-20T20:15:31Z")}}]
But how can you reference the parent element $.updatedon for the comparison?
In plain mongodb shell query language it would aleady be of help.
But I am actually accessing it using c# driver, so my query filter is like this:
FilterDefinition<_visitorData> filter;
filter = Builders<_visitorData>.Filter
.Gte(f => f.updatedon, DateTime.Now.AddDays(-15));
filter = filter & (
Builders<_visitorData>.Filter
.Exists(f => f.carts, false)
| !Builders<_visitorData>.Filter.ElemMatch(f =>
f.carts, c => c.closed && c.updatedon > DateTime.Now.AddDays(-15)
)
);
How can I replace DateTime.Now.AddDays(-15) with a reference to the document root element updatedon?
You can project the difference of carts.updatedon and updatedon and then filter out the results from this aggregation pipeline.
coll.aggregate([{'$unwind':'$carts'},
{'$match':{'closed':{'$ne':true}}},
{'$project':{'carts.cartid':1,'carts.status':1,'carts.cart_created':1,'carts.closed':1,'carts.items':1,'carts.updatedon':1,'updatedon':1,'diff':{'$subtract':['$carts.updatedon','$createdon']}}},
{'$match': {'diff': {'$gte': 1000 * 60 * 60 * 24 * days}}}])
days = 3 will filter out results more than 3 days difference documents.
I have just given the example of how you can use $subtract to find date difference and filter documents based on that.
well I was in a similar situation few days back.
I tackled it by using Jobject of Newtonsoft.Json.
Create a function to return bool which actually process each document take it as input.
Jobject jOb=Jobject.parse(<Your document string>);
JArray jAr=JArray.Parse(jOb["carts"]);
If(jOb["updateon"]=<Your Business Validation>)
{
foreach(var item in jAr)
if(item["closed"]==<Your validation>){ return true}
}
return false;
I hope this helps :)
If you handling with any null values in those properties then please use Tryparse and out variable.
I have a document like this:
{ "File" : "xxxxxxx.txt",
"Content" : [
{ "tag" : "Book",
"name" : "TestBook1",
"value" : "xxx"
},
{ "tag" : "Dept",
"name" : "TestDept1",
"value" : "yyy"
},
{ "tag" : "Employee",
"name" : "TestEmployee1",
"value" : "zzz"
}]
}
I can find the document by using:
var filter = Builders<BsonDocument>.Filter.Eq("Content.tag", "Dept");
var result = collection.Find(filter).ToList();
However, this returns the whole document. Is there any way to just get the JSON object ({"tag" : "Dept", "name" : "TestDept1"})?
What I'm trying to get is just the "value" property (in this case, it's "yyy"), instead of the whole document.
UPDATE:
Like Phani suggested, I was able to make this work with the following code:
var subFilter = Builders<BsonDocument>.Filter.Eq("tag", "Dept");
var filter = Builders<BsonDocument>.Filter.ElemMatch("Content", subFilter);
var result =
collection.Find(filter)
.Project(Builders<BsonDocument>.Projection.Exclude("_id").Include("Content.$"))
.ToList();
You need to use the ElemMatch projection for this.
Shell query for this : db.testing.find({Content:{$elemMatch:{"tag":"Dept"}}},{"_id":0,"Content.$":1})
C# query will be
Find(x => x.Content.Any(p => p.tag == "Dept")).Project(Builders<BsonDocument>.Projection.Exclude("_id").Include("Content.$")).ToList();
Please check if this is working.
Below is an example of my document. I am trying to update the CostReports part based on the id of the CostReportingPeriods element.
{
"_id" : "240106",
"CostReportingPeriods" : [
{
"FyBgnDt" : ISODate("2000-01-01T05:00:00.000Z"),
"FyEndDt" : ISODate("2000-12-31T05:00:00.000Z"),
"_id" : "240106-20000101-20001231",
"CostReports" : []
},
{
"FyBgnDt" : ISODate("2001-01-01T05:00:00.000Z"),
"FyEndDt" : ISODate("2001-12-31T05:00:00.000Z"),
"_id" : "240106-20010101-20011231",
"CostReports" : []
},
{
"FyBgnDt" : ISODate("2002-01-01T05:00:00.000Z"),
"FyEndDt" : ISODate("2002-12-31T05:00:00.000Z"),
"_id" : "240106-20020101-20021231",
"CostReports" : []
},
{
"FyBgnDt" : ISODate("2003-01-01T05:00:00.000Z"),
"FyEndDt" : ISODate("2003-12-31T05:00:00.000Z"),
"_id" : "240106-20030101-20031231",
"CostReports" : []
}
]
I am using the following code to try and update that element but am getting an error that says cannot use the element (CostReportingPeriods of CostReportingPeriods.CostReports) to traverse the element. If I add CostReportingPeriods.0.CostReports it will add it to the first element of the array, regardless of the filter.
var builder = Builders<MongoModels.Provider>.Filter;
var filter = builder.Eq("_id",costReport.PRVDR_NUM) & builder.Eq("CostReportingPeriods._id", costReport.UNIQUE_ID);
var update = Builders<MongoModels.Provider>.Update.AddToSet("CostReportingPeriods.CostReports", Mapper.Map<CostReport, MongoModels.CostReport>(costReport, opt =>
{
opt.AfterMap((src, dest) => dest.Worksheets = CreateWorksheets(dest.RptRecNum).ToList());
}));
How do I get it to update the element I want it to update based on the id of the subdocument?
After trying a bunch of different things, by channging my update filter from "CostReportingPeriods.CostReports" to "CostReportingPeriods.$.CostReports" it works flawlessly.
we have a problem with our indexes. We have an index on our emails but it throws errors like such:
> db.User.insert({email: "hell33o#gmail.com", "_id" : BinData(3,"iKyq6FvBCdd54TdxxX0JhA==")})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error index: placetobe.User.$email_text dup key: { : \"com\", : 0.6666666666666666 }"
}
})
when we have the index created with our C# driver like this
Created by C# with:
CreateIndexOptions options = new CreateIndexOptions {Unique = true};
_collection.Indexes.CreateOneAsync(Builders<User>.IndexKeys.Text(_ => _.email), options);
resulted in
{
"v" : 1,
"unique" : true,
"key" : {
"_fts" : "text",
"_ftsx" : 1
},
"name" : "email_text",
"ns" : "placetobe.User",
"weights" : {
"email" : 1
},
"default_language" : "english",
"language_override" : "language",
"textIndexVersion" : 2
}
but if we create it with the MongoDB console like this it works:
{
"v" : 1,
"unique" : true,
"key" : {
"email" : 1
},
"name" : "email_1",
"ns" : "placetobe.User"
}
I don't understand the difference between the two indexes, but they have an effect on our DB. We also have problems with a Collectin that saves names. we get duplicate exceptions on "Molly" if we try to insert "Molli". With the emails is seems to give us errors whenever we have two "gmail" emails in the collection or two ".com" emails etc.
This is a University project and we have to turn it in tomorrow. we're really in trouble, help would be much appreciated
You don't want your email to be a text Index. Text indices allow you to search large amounts of text in MongoDB like if you were parsing through comments or something. All you want is to make sure your emails aren't duplicated so you should use an ascending or descending index.
CreateIndexOptions options = new CreateIndexOptions {Unique = true};
_collection.Indexes.CreateOneAsync(Builders<User>.IndexKeys.Ascending(_ => _.email), options)