MongoDB remove a subdocument document from a subdocument - c#

I use 10gen C# driver for MongoDB and I would like to remove a subdocument from a subdocument. I don't know how to do it.
Here's an example of what looks like my document
{
"_id": "binary_stuff",
"Name": "MyApplication",
"Settings": [
{
"_id": "binary_stuff",
"Key": "ImportDirectory",
"Value": "C:\data",
"Overrides": [{
"_id": "binary_stuff",
"Name": "PathDirectory",
"Value": "C:\anotherData"
}]
},
}
And I want to delete the Override which Name is PathDirectory. Here's the query I wrote but it doesn't work. I have no error.
var query = Query.And(Query.EQ("_id", applicationId), Query.EQ("Settings.Key", "ImportDirectory"), Query.EQ("Settings.$.Overrides.Name", "PathDirectory"));
Run(database => database.Applications().Remove(query));
Thanks for any help.
John

you should to use $pull operation for delete item from array.
var query = Query.And(Query.EQ("_id", applicationId),
Query.EQ("Settings.Key", "ImportDirectory"));
var update = Update.Pull("Settings.$.Overrides", new BsonDocument(){
{ "Name", "PathDirectory" }
});
database.Applications().Update(query, update);

Related

Write Json document to mongoDB using C#

I have a CSV file which contains
Name, EmployeID
Kishore, 235
I need to read Name & EmployeID from above csv file, update name and EmployeID in below JSON and write updated Json to mongodb collection.
{
"name": kishore,
"EmployeID": "235",
"Gender": "Male",
}
Can you please help me with any code snippet using C#
Appreciate your help
The simplest form to mimic the insert statement from your comment is to use a collection of type BsonDocument and insert the document like this:
var client = new MongoClient("MONGODB_CONNSTR");
var db = client.GetDatabase("MONGODB_DB_NAME");
var employees = db.GetCollection<BsonDocument>("employees");
await employees.InsertOneAsync(new BsonDocument
{
{ "EmployeeId", 235 },
{ "Name", "kishore" },
{ "Gender", "Male" }
});
This creates the following document:
{
"_id": {
"$oid": "62d7b6d25c248b9684eee64d"
},
"EmployeeId": 235,
"Name": "kishore",
"Gender": "Male"
}

elasticsearch c# nest advanced search

I have a problem about querying a complex data type with c# nest api in elasticsearch. My model in elasticsearch is like this:
"hits": [
{
"_index": "post",
"_type": "postmodel",
"_source": {
"projectId": "2",
"language": "en",
"postDate": "2017-06-11T08:39:32Z",
"profiles": [
{
"label": "Emotional",
"confidence": 1
}
]
}
},
{
"_index": "post",
"_type": "postmodel",
"_source": {
"projectId": "3",
"language": "en",
"postDate": "2017-06-11T08:05:01Z",
"profiles": [
{
"label": "Fact oriented",
"confidence": 0.69
},
{
"label": "Rational",
"confidence": 1
}
]
}
},
...
By using c# Nest API, i want to fetch the postmodels which is projectId=3 and with "Rational" profile. My current code looks like this:
var postModels = await _elasticClient.SearchAsync<PostModel>(s => s
.Index("post")
.Query(q =>
{
QueryContainer query = new QueryContainer();
query = query && q.Match(m => m.Field(f => f.ProjectId)
.Query("3"));
return query;
}));
But i dont know how to query "Profiles". i want to extend my query to fetch specific profiles as well. I would be happy if someone can help me with this problem. Thank you in advance.

Linq query to Json string

starting from a JObject I can get the array that interests me:
JArray partial = (JArray)rssAlbumMetadata["tracks"]["items"];
First question: "partial" contains a lot of attributes I'm not interested on.
How can I get only what I need?
Second question: once succeeded in the first task I'll get a JArray of duplicated items. How can I get only the unique ones ?
The result should be something like
{
'composer': [
{
'id': '51523',
'name': 'Modest Mussorgsky'
},
{
'id': '228918',
'name': 'Sergey Prokofiev'
},
]
}
Let me start from something like:
[
{
"id": 32837732,
"composer": {
"id": 245,
"name": "George Gershwin"
},
"title": "Of Thee I Sing: Overture (radio version)"
},
{
"id": 32837735,
"composer": {
"id": 245,
"name": "George Gershwin"
},
"title": "Concerto in F : I. Allegro"
},
{
"id": 32837739,
"composer": {
"id": 245,
"name": "George Gershwin"
},
"title": "Concerto in F : II. Adagio"
}
]
First question:
How can I get only what I need?
There is no magic, you need to read the whole JSON string and then query the object to find what you are looking for. It is not possible to read part of the JSON if that is what you need. You have not provided an example of what the data looks like so not possible to specify how to query.
Second question which I guess is: How to de-duplicate contents of an array of object?
Again, I do not have full view of your objects but this example should be able to show you - using Linq as you requested:
var items = new []{new {id=1, name="ali"}, new {id=2, name="ostad"}, new {id=1, name="ali"}};
var dedup = items.GroupBy(x=> x.id).Select(y => y.First()).ToList();
Console.WriteLine(dedup);

Retrieve an array containing a BSON document

I am trying to retrieve an array containing a BSON document using C#. Below is the document structure and the code that I'm using in order to do that.
"_id": 199,
"name": "Rae Kohout",
"scores": [{
"type": "exam",
"score": 82.11742562118049
},
{
"type": "quiz",
"score": 49.61295450928224
},
{
"type": "homework",
"score": 28.86823689842918
},
{
"type": "homework",
"score": 5.861613903793295
}]
}
var db = client.GetDatabase("school");
var studentCol = db.GetCollection<BsonDocument>("students");
var builderDoc = Builders<BsonDocument>.Filter;
var filter=builderDoc.ElemMatch("scores", builderDoc.Eq("type","homework" ));
var result = studentCol.Find(filter);
When I execute this statement, the value of the result is coming as {find({ "scores" : { "$elemMatch" : { "type" : "homework" } } })}. If I apply .tolist(), I am seeing the data coming properly, but as a generic collection, where I'm not able to do any mongo querying on it.
How can I retrieve the document as an array?

Querying JSON with JSON .NET

{
"kind": "folderTree",
"data":
[
{
"id": "IEAAALNZI7777777",
"title": "Root",
"childIds":
[
"IEAAALNZI4ADAKBQ",
"IEAAALNZI4ADAMBQ",
"IEAAALNZI4ADAMBR"
],
"scope": "WsRoot"
},
{
"id": "IEAAANE7I7777777",
"title": "Root",
"childIds":
[
"IEAAANE7I4AC2NTX"
],
"scope": "WsRoot"
},
{
"id": "IEAAALNZI7777776",
"title": "Recycle Bin",
"childIds":
[
"IEAAALNZI4ADALZ2",
"IEAAALNZI4ADAL52",
"IEAAALNZI4ADALR3"
],
"scope": "RbRoot"
}
]
}
Im trying to query the following json structure, searching the child items I want to return the id for a given title.
I am trying something like this:
var folder = json["data"].Children().Where(x => x["Title"] == "Root");
But I'm not sure of the correct syntax
You can use SelectTokens to query LINQ to JSON objects. It supports JSONPath query syntax including wildcards. You can then further narrow down the search with a Where clause:
var folders = json.SelectTokens("data[*]").Where(t => (string)t["title"] == "Root").ToList();
It also supports filtering of array entries based on property values if you don't want the extra Where clause:
var folders = json.SelectTokens("data[?(#.title == 'Root')]").ToList();
Both of the above do the same thing. Incidentally, you've got two folders whose title is "Root" in your JSON, so your query will return multiple results.

Categories