query array using mongo for C# - c#

I have the following json
{
"_id" : ObjectId("4f7ee46e08403d063ab0b4f9"),
"name" : "MongoDB",
"notes" : [
{
"title" : "Hello MongoDB",
"content" : "Hello MongoDB"
},
{
"title" : "ReplicaSet MongoDB",
"content" : "ReplicaSet MongoDB"
}
]
}
I am able to query a specific document in this manner:
db.collection.find({ "notes.title" : "Hello MongoDB"});
How do I go about creating the above query using FilterDefinition?
I am using Mongo for C#

var filter = Builders<BsonDocument>.Filter.Eq("notes.title", "Hello MongoDB");
the above should work for you.

Related

Deleting a mongodb subdocument inside another that is inside another?

I have read other posts similar to this one, but since I am new to mongodb and the depth of the subdocument that I have is more then already addressed, I have to ask this question here. My document is as follows:
{
"_id" : "57bae0ad7bbba417fcaec4ca",
"spUserProfile" : null,
"spLinkedBusinesses" : [
{
"_id" : "57bae0ad7bbba417fcaec4c9",
"businessDocuments" : [
{
"_id" : "57bae0fb7bbba417fcaec4cc",
"documentPath" : "/docs/doc1.pdf",
"documentName" : "Doc Hey",
"documentType" : "DPF",
"documentUploadDateTime" : ISODate("2016-08-22T11:24:43.061Z")
},
{
"_id" : "57bae0fd7bbba417fcaec4cd",
"documentPath" : "/docs/doc_mute.pdf",
"documentName" : "Agreements IMP",
"documentType" : "PDF",
"documentUploadDateTime" : ISODate("2016-08-22T11:24:45.229Z")
},
{
"_id" : "57bae0ff7bbba417fcaec4ce",
"documentPath" : "/docs/accounts1.xls",
"documentName" : "Expenses 1",
"documentType" : "XLS",
"documentUploadDateTime" : ISODate("2016-08-22T11:24:47.066Z")
}
]
}
]
}
I have to delete the businessDocuments with id "57bae0fd7bbba417fcaec4cd" (using c# mongodb driver code), the collection is called RefUsers.
PS: I cant use the legacy C# mongodb drivers, so no use of the Query class.
thanks.
Have a look into $pull to remove documents from an embedded array
Pull MongoDB documentation
ElemMatch will also be useful to you here if you are wanting to identify items within embedded arrays
ElemMatch MongoDB documentation

Using c# Mongodb driver 2.2, how to find max record when grouped by on a particular field

I have a collection as "UserRecords". structure for this is as follows
{
"_id" : "ee654ce6-e50d-4243-8738-35c087a85e67",
"_t" : "Animals",
"ClickedOn" : NumberLong(1452600122),
"Category" : "Nature",
"UserId" : "a1",
}
{
"_id" : "ee654ce6-e50d-4243-8738-35c087a85e67",
"_t" : "Abstract",
"ClickedOn" : NumberLong(1247634566),
"Category" : "Modern",
"UserId" : "a1",
}
{
"_id" : "ee654ce6-e50d-4243-8738-35c087a85e67",
"_t" : "Abstract",
"ClickedOn" : NumberLong(1247634440),
"Category" : "Modern",
"UserId" : "a1",
}
and more...
now I want to get Max clicked on for each category. Using latest Mongo C# driver
something like
select Max(clicked) from table group by Category in SQL.
Queries like this can be efficiently processed with the MongoDB Aggregation Framework. However, the queries are written as JSON, making them a bit hard to read.
var dataCollection = Database.GetCollection("UserRecords");
var AggArgs = new AggregateArgs {
Pipeline =
new[] {BsonDocument.Parse(#"{$group : {_id : '$Category', ClickedOn : {$max : '$ClickedOn'}}}")}
};
foreach (var result in dataCollection.Aggregate(AggArgs))
{
Console.WriteLine($"Category: {result["_id"]} Clicked: {result["ClickedOn"]}");
}

Assign JSON value to property in C#

From an API I receive a JSON-object that looks like this:
{
"wind" : {
"speed" : 7.31,
"deg" : 187.002
},
"rain" : {
"3h" : 0
},
"clouds" : {
"all" : 92
},
"coord" : {
"lon" : 139,
"lat" : 35
},
"dt" : 1369824698,
"id" : 1851632,
"cod" : 200,
"weather" : [
{
"id" : 804,
"main" : "clouds",
"icon" : "04n",
"description" : "overcast clouds"
}
],
"main" : {
"humidity" : 89,
"temp_max" : 292.04,
"temp_min" : 287.04,
"temp" : 289.5,
"pressure" : 1013
},
"sys" : {
"country" : "JP",
"sunrise" : 1369769524,
"sunset" : 1369821049
},
"name" : "Shuzenji"
}
I would like to assign two of these values to my class:
public class Weather {
public string Name { get; set; }
public string Temp { get; set; }
}
The name I can assign like this:
weather.Name = TheJSON.name.ToString();
But the temp is trickier, because it's nested inside the "main"-array. I´ve seen many examples on how to do this in Javascript but not so much in C#. Thanks!
Main is not an array. It is an object, so
TheJSON.main.temp.ToString()
The easiest way to work with JSON data is to deserialize them as C# objects and directly use them in your application. You can use a tool like JSON C# Class Generator to automatically generate the C# class from the JSON data. Once you have your C# classes generated, you can deserialize the JSON string using the JsonConvert.DeserializeObject(jsonText); The generated code requires Newtonsoft Json.NET which you can easily add as a NuGet package.
If you save your JSON content in D:\test.json, you can use the following code to access the values using the C# objects generated. The example below is to just give you an idea on the usage.
var json = File.ReadAllText(#"D:\test.json");
var weather = JsonConvert.DeserializeObject<Weather>(json);
Console.WriteLine(weather.Name);
Console.WriteLine(weather.Sys.Country);

Mongo deepFind?

I Have a mongoDB that contains data in unknown structure, and I want to find all the documents that has a specific BsonElement. Can I do it without the knowledge about the documents structure?
For example, if the documents look like this (and I don't know that) can I find all the documents that has "DBType":"MSSQL"?
There is somting like collection.deepFind(QueryDocument);?
{
"_id" : ObjectId("528fe1602feaa3231c784d92"),
"CurrentJobs" : {
"_t" : "sqQueryJob",
"IsDone" : false,
"ExecuteTime" : ISODate("2013-11-22T22:57:35.733Z"),
"Result" : { },
"DB" : {
"DBType" : "MSSQL",
"Name" : "Data",
"Host" : ".",
"ServiceName" : "DataBase",
"Port" : "1521",
},
"QueryResult" : null,
"Query" : "."
}
}
Thanks!

how to find a sum using linq in a bson document using C#

The sample collections structure is :-
{
arr : [
{ "seq" : 2 },
{ "seq" : 4 }
]
}
The C# code i tried is
var maxTicketSeq = bsonTrans["arr"].AsBsonArray.Sum(m => (int)m["seq"]);
this is working fine...
But for this structure
{
"arr" : [
{ "name" : [{"seq" : 2 } , {"seq" : 5 }] },
{ "name" : [{"seq" : 2 } , {"seq" : 5 }] }
}
for this i need to find the sum of seq.
how to achieve this in linq query.
Actually that bsonDocument is similar to the one which i am getting as result of a mongo query.

Categories