MongoDB - Update or Insert object in array in C# - c#

I have the following collection
{
"_id" : ObjectId("57315ba4846dd82425ca2408"),
"myarray" : [
{
userId : ObjectId("570ca5e48dbe673802c2d035"),
point : 5
},
{
userId : ObjectId("613ca5e48dbe673802c2d521"),
point : 2
},
]}
and I want to add a new element to this array in C#, Could please to help me I try to do it's by $push but always give me this error. thanks
MongoDB.Driver.AddToSetUpdateDefinition<TDocument, TItem>.Render(IBsonSerializer<TDocument> documentSerializer, IBsonSerializerRegistry serializerRegistry)`enter code here`

Related

Mongodb Update or insert in c#

I want to update or insert into to mongo collection "Member". Under this collection i have an array MagazineSubscription. Here magazine Code is unique. Please refer the sample JSON.
So if need to update or insert into mongo using C# mongo driver.
First I need to check this code exist
2, If it exist update one
If it does not exist insert.
Is there any way I can do in one step. Like if it already exist update otherwise insert. Instead of hit twice. Because my collection is very big.
{
"_id" : ObjectId("5c44f7017en0893524d4e9b1"),
"Code" : "WH01",
"Name" : "Lara",
"LastName" : "John",
"DOB" : "12-10-2017",
"Gender" : "Male",
"Dependents" : [
{
"RelationShip" : "Son",
"Name" : "JOHN",
"DOB" : "01-01-1970",
"Gender" : "Male",
"Address" : "Paris",
"ContactNumber" : "+312233445666"
},
{
"RelationShip" : "Wife",
"Name" : "Marry",
"DOB" : "01-01-1980",
"Gender" : "Female",
"Address" : "Paris",
"ContactNumber" : "+312233445666"
}
]
"Matrimony" : [
{
"Fee" : 1000.0,
"FromDate" : "01-01-2015",
"ToDate" : "01-01-2017",
"Status" : false
}
],
"MagazineSubscription" : [
{
"MagazineCode" : "WSS",
"DateFrom" : "01-05-2018",
"DateTo" : "01-01-2020",
"PaidAmount" : 1000.0,
"ActualCost" : 1500.0,
"Status" : false,
"DeliveryStatus" : [
{
"ReturnedDate" : "10-01-2019",
"Comment" : "Returned because of invalid address"
},
{
"ReturnedDate" : "10-02-2019",
"Comment" : "Returned because of invalid address"
}
]
}
]
}
Use mongodb's update operation with upsert:true.
Please refer here: https://docs.mongodb.com/manual/reference/method/db.collection.update/
Here's a sample from the page:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>, //you need this option
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
And here's a similar question according to what you need:
Upserting in Mongo DB using official C# driver
EDIT 1
Steps:
First you need to write a filter to scan if the document exists. you can check any number of keys (Essentially a document).
Write the update section with the keys you'd like to update (Essentially a document).
Set upsert to true.
Mongodb will use your filter to search the document. If found, it will use the update section to perform the update mentioned by you.
In case the document does not exist, a new document will be created by using the filter keys + keys in the update part.
Hope that makes things clear as I have never used a C# mongo driver. So I won't be able to provide you the exact syntax.
EDIT 2
I'm providing #jeffsaracco's solution here:
MongoCollection collection = db.GetCollection("matches");
var query = new QueryDocument("recordId", recordId); //this is the filter
var update = Update.Set("FirstName", "John").Set("LastName","Doe"); //these are the keys to be updated
matchCollection.Update(query, update, UpdateFlags.Upsert, SafeMode.False);

Nested array $pull query using C# MongoDB driver

I have this following query working on mongo shell as expected.
db.getCollection('personnels').update(
{
_id: ObjectId("55f6728b9d73a15807885de8"),
"Devices._id":ObjectId("55fa5f7ac9e7863a3836e331")
},
{
$pull:{ "Devices.$.DeviceCloudFolders": { "CloudFolderId": ObjectId("5615124b06275f072040c4f1")}}
}
);
And here is my document structure:
{
"_id" : ObjectId("55f6728b9d73a15807885de8"),
"FirstName" : "Tolga",
"Devices" : [
{
"_id" : ObjectId("55fa5f7ac9e7863a3836e331"),
"Name" : "tolga-laptop",
"DeviceCloudFolders" : [{
"AuthorityType" : 1,
"CloudFolderId" : ObjectId("55f96db5c9e7863a3836e310"),
"Status" : 1
}],
"Status" : 1
}
],
"Status" : 1
}
I need to use it in C# and couldn't figure out how.
I started with these lines:
var filter = Builders<Personnel>.Filter.And(
Builders<Personnel>.Filter.Eq("_id", ownerPersonnelId),
Builders<Personnel>.Filter.Eq("Devices._id", _id));
var update = Builders<Personnel>.Update.PullFilter("Devices.$.DeviceCloudFolders", /*couldn't figure out what goes here*/))
Personnels.FindOneAndUpdateAsync(filter, update);
I'm not sure, but you can try using this:
var update = Builders<Personnel>.Update.PullFilter(
"Devices.$.DeviceCloudFolders",
Builders<DeviceCloudFolder>.Filter.Eq("CloudFolderId", _cloudFolderId));

"Extra" nesting in MongoDB C# driver

I have some document stored in MongoDB (2.4.9) with and array if documents field:
{
"_id" : "some id",
"class" : "somevalue",
...
"externalAlarmDefinition" : [
{
"idx" : 1,
"inputId" : 1
},
{
"idx" : 2,
"inputId" : 2
},
...
{
"idx" : 6,
"inputId" : 7
}
]
}
For some reason, when I query this object I get BsonElement who's value is a BsonArray with one element - that element in turn is another BsonArray which contains the actual BsonDocuments. See image for the structure:
Does this make sense? I expected that the value of the BsonElement would be a BsonArray with the 6 BsonDocuments.
Am I missing something - can someone explain this?
I am using Mongo Driver 1.9.1.221 that I got using nuget

Mongodb: How can I check if a point is contained in a polygon?

I've got a list of points of a area in an array of points (latitude, longitude). I 've made an index on these arrays and now I want to know if one point is inside that polygon.
Is it possible with MongoDB?
I already tried with these commands but no luck:
> polygonA = [ [ 48.780809,2.307129],[ 48.781809,2.300129],[ 48.770809,2.317129]]
> db.contours.find({ "rings.ring" : { "$within" : { "$polygon" : polygonA } } })
and
> db.runCommand( { geoNear : "contours" , within : [2.307129,48.780809,], num : 10 } );
My data structure is:
> db.contours.findOne({},{'rings':0})
{
"_id" : ObjectId("50364617d591ac166000c196"),
"foundfieldname" : "Name",
"geometrytype" : "geometryPolygon",
"attributes" : {
"Shape" : "Polygon",
"Name" : "France",
"Type" : "Country",
"Country" : "France",
"Area" : "1162358716567.45"
},
"country" : "France",
"rings":{
"ring":[[12.32,43.54],...],
...
}
Thanks
This requires that rings.ring be a points and that it have a geo index defined on it, is that the case here?
Your question implies that this is in fact a list of multiple points with a standard index on it (multikey index), which is not going to work.
http://www.mongodb.org/display/DOCS/Geospatial+Indexing/#GeospatialIndexing-BoundsQueries
As you can see there, when you search for "loc" as a point inside a polygon, the "loc" field is something like this (see the link above for other valid examples):
{ loc : [ 50 , 30 ] }
With an index something like this:
db.places.ensureIndex( { loc : "2d" }
That is, a field representing a single point and with a geo index defined on it. If you use a field like that - does your testing then work?

Insert in to a nested array Using C# Official Driver MongoDB

Here is my exact schema:
{
"_id" : ObjectId("4fb4fd04b748611ca8da0d48"),
"Name" : "Categories",
"categories" : [{
"_id" : ObjectId("4fb4fd04b748611ca8da0d46"),
"name" : "Naming_Conventions",
"sub-categories" : [{
"_id" : ObjectId("4fb4fd04b748611ca8da0d47"),
"name" : "Namespace_Naming",
"standards" : []
}]
}]
}
As you can see I have an array named "standards" nested way down in there. How would I programmatically insert in to that using the C# driver? I have tried all of the examples I have found online but none of them are working.
Something like the below. Obviously, if any of these are not present on the way down to it, you're going to get a null reference exception.
var doc = collection.FindOne(Query.EQ("_id", new ObjectId("4fb4fd04b748611ca8da0d48")));
var standards = doc["categories"]
.AsBsonArray[0]
.AsBsonDocument["sub-categories"]
.AsBsonArray;
standards.Add(new BsonDocument());
collection.Save(doc);

Categories

Resources