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!
Related
I try to get all keys and values type in all levels of a mongo collection. I have something like:
"CRM" : {
"Teste" : "true"
},
"Endereco" : {
"Cidade" : "MARINGA",
},
"Vendas" : [
{
"idP" : NumberInt(34),
"txt" : "001"
},{
"idP" : NumberInt(34),
"txt" : "002"
}
],
"Tipos" : [
{
"idT" : NumberInt(34),
"idTipo" : NumberInt(34)
},{
"idT" : NumberInt(34),
"idTipo" : NumberInt(34)
}
]
}
I want return like this:
CRM.Teste : Boolean,
CRM.Endereco.Cidade : String,
Vendas[].idP : NumberInt(34),
Vendas[].txt : String,
Tipos[].idT : NumberInt(34),
Tipos[].idTipo : NumberInt(34)
I don't have a model, is there some function in mongo driver or linq that return this?
Iam using MongoDB C#/.NET Driver version 2.11.5. Here is my collection structure.
CollectionName: Deployment
{
"_id" : ObjectId("60263b3279357e12775bfb21"),
"version" : "P3-V1.0",
"productId" : "6020f75d103d4895f12c88ec",
"hierarchy" : "6020f8ad103d4895f12c88ed",
"description" : "P3-T1-V1.0",
"policies" : [
{
"name" : "Policy-1",
"description" : "Policy-1",
"rules" : [
{
"subject" : "abc.def#xyz.com",
"status" : "InProgress",
"comments" : "",
"updatedBy" : "",
"approvalId" : "8f7c8767-6613-4aa2-9b87-7778a42512bd",
"requestDate" : ISODate("2021-02-12T08:29:32.000Z")
},
{
"subject" : "ghi.jkl#xyz.com",
"status" : "InProgress",
"comments" : "",
"updatedBy" : "",
"approvalId" : "9e7c8767-6613-4aa2-9b87-7778a42512ee",
"requestDate" : ISODate("2021-02-11T08:29:32.000Z")
}
]
},
{
"name" : "Policy-2",
"description" : "Policy-2",
"rules" : [
{
"subject" : "mno.pqr#xyz.com",
"status" : "InProgress",
"comments" : "",
"updatedBy" : "",
"approvalId" : "1a6c8767-6613-4aa2-9b87-7778a42512bd",
"requestDate" : ISODate("2021-02-12T08:29:32.000Z")
},
{
"subject" : "stu.vwx#xyz.com",
"status" : "InProgress",
"comments" : "",
"updatedBy" : "",
"approvalId" : "2z0c8767-6613-4aa2-9b87-7778a42512ee",
"requestDate" : ISODate("2021-02-11T08:29:32.000Z")
}
]
}
]
}
C# Class Names:
Deployment (has multiple IList<Policy> Policies)
Policy (has multiple IList<Rule> Rules)
Rule
What is the Update query to update status, comments and updatedBy fields in a Rule, given Policy.Name (for ex: Policy-1) and Rule.subject (for ex: abc.def#xyz.com)?
What is the Insert query to insert a new Rule object inside a Policy, given Policy.Name (for ex: Policy-1)?
Thanks for your help.
With reference to the question -
Querying, filtering and updating multiple level nested arrays in MongoDB using C#
I have implemented the following and it worked as expected.
var updateFilter = Builders<Deployment>.Filter.Eq(f => f.Id, deployment.Id);
var updateBuilder = Builders<Deployment>.Update
.Set("policies.$[i].rules.$[j].comments", rule.Comments)
.Set("policies.$[i].rules.$[j].completionDate", rule.CompletionDate)
.Set("policies.$[i].rules.$[j].status", Enum.GetName(rule.Status))
.Set("policies.$[i].rules.$[j].updatedBy", rule.UpdatedBy);
var arrayFilters = new List<ArrayFilterDefinition>()
{
new BsonDocumentArrayFilterDefinition<Policy>(new BsonDocument("i.name", policy.Name)),
new BsonDocumentArrayFilterDefinition<Rule>(new BsonDocument("j.subject", rule.Subject))
};
var updateOptions = new UpdateOptions()
{
ArrayFilters = arrayFilters
};
await _deploymentRepository.UpdateOneAsync(updateFilter, updateBuilder, updateOptions);
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
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"]}");
}
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);