I want to retrieve New_amt field from following document using C# :
> db.Customer.find().pretty()
{
"_id" : ObjectId("5c6daad5fc5bef1b941bec3c"),
"Customer_Id" : "1",
"Name" : "aaaaa",
"Address" : "lalalal",
"PhoneNo" : "7878787",
"OptionalNo" : "7878787",
"Date" : ISODate("2019-02-20T19:30:29.095Z"),
"Installment" : [
{
"id" : ObjectId("5c6dab0bfc5bef1b941bec3f"),
"New_amt" : "0",
"Net_amt" : "6000",
"Paid" : "200",
"Remains" : "5800",
"Date" : ISODate("2019-02-20T19:31:23.772Z")
}
]
}
you need MongoDriver to c#, one time you have that
instance it
var _client = new MongoClient("mongodb://localhost:27017");
var _database = _client.GetDatabase("YOUR DATABASE");
var _bitCollection = _database.GetCollection<MODEL>("YOUR COLLECTION");
one time you have that you can filter it
var filter = Builders<MODEL>.Filter.Eq(fieldName, fieldValue);
var result = await _bitCollection.Find(filter).ToListAsync();
and result return a List, if don't have model you can use
dynamic as model, but it have some many problems sometimes
Related
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));
I try to perform bulk update operation using Official Mongo c# 2.0 driver via the following code :
var query =
Builders<Profile>.Filter.In(p => p.userId, listBounce.Values.ToList()) &
Builders<Profile>.Filter.In(p => p.ID, listBounce.Keys.Select(x=> new ObjectId(x)).
ToList());
var update = Builders<Profile>.Update.Set(p => p.MailLists[-1].Status, (int)wrongEmailStatusAssetId);
dbCollection.UpdateManyAsync(query, update).Wait();
But there is the following error has been occurred
{"A write operation resulted in an error.\r\n
The positional operator did not find the match needed from the query.
Unexpanded update: p2l.$.status"}
I need to update each element's property in array which matches the query.
The documents structure is :
{
"_id" : ObjectId("55eeb5da965bb036984110b9"),
"created" : ISODate("2015-09-08T10:17:59.784Z"),
"userId" : 13929,
"email" : "go-get#yandex.ru",
"firstName" : "Skrillex",
"lastName" : "Skrillex",
"phoneNumber" : "",
"isUnsubscribed" : false,
"isAboveLimit" : false,
"status" : 0,
"userAgent" : 9760,
"isDeleted" : false,
"p2l" : [
{
"listId" : 45165,
"status" : 131,
"subscriptionDate" : ISODate("2015-09-04T06:24:55.763Z")
}
]
}
Just add Builders<Profile>.Filter.Exists(p=>p.MailLists) to query and the issue could be solved.
This is a sample structure of a collection i am having in mongodb, likewise some 60+ lakh similar records are there in one collection. We moved to mongodb seeing the fast accessing performance,but now its bit hard to say evean simple searching is taking huge time. I have given index for the search params. For name searching (search params MNG_FIRST_NAME, MNG_MIDDLE_NAME, MNG_LAST_NAME, MNG_ALIASIST.AKAFIRST_NAME, MNG_ALIASIST.AKALAST_NAME).
Please consider is the method i'm following the correct way with mongodb.
Please find the code sample and collection structure below i'm using.
{
"_id" : ObjectId("5308e2e1f525bc0f0472cbf6"),
"MNG_UID" : "1389120",
"MNG_CATEGORY" : "OFFICER",
"MNG_FIRST_NAME" : "JOHN",
"MNG_LAST_NAME" : "DOE",
"MNG_MIDDLE_NAME" : "MARK",
"MNG_CREATEDON" : "2010-11-19",
"MNG_UPDATEDON" : "2014-01-01",
"MNG_TITLE" : "Dr",
"MNG_REMARKS" : "",
"MNG_TYPE" : "WORLDCHECK",
"MNG_PROGRAMLIST" : [],
"MNG_IDLIST" : [],
"MNG_ALIASIST" : [
{
"AKAUID" : "101",
"AKATYPE" : "ALIAS",
"AKACATEGORY" : "",
"AKAFIRST_NAME" : "JOHNNY TURA, DOE",
"AKALAST_NAME" : ""
},
{
"AKAUID" : "102",
"AKATYPE" : "ALIAS",
"AKACATEGORY" : "",
"AKAFIRST_NAME" : "MARK TURA, DOE",
"AKALAST_NAME" : ""
}
],
"MNG_ADDRESSLIST" : [
{
"ADDRESSUID" : "",
"ADDRESS1" : "Dakar",
"ADDRESS2" : "Dakar",
"ADDRESS3" : "SENEGAL",
"ADDRESSCITY" : "Dakar",
"ADDRESSCOUNTRY" : "SENEGAL",
"ADDRESSPOCODE" : "",
"ADDRESSSTATE" : "Dakar"
}
],
"MNG_NATIONALITYLIST" : [
{
"NATUID" : "",
"NATCOUNTRY" : "ISRAEL",
"NATMAINENTRY" : ""
},
{
"NATUID" : "",
"NATCOUNTRY" : "AMERICIAN",
"NATMAINENTRY" : ""
}
],
"MNG_CITIZENSHIPLIST" : [],
"MNG_DOBLIST" : [],
"MNG_PLACEOBLIST" : [],
"MNG_ADDINFOLIST" : []
}
code used to obtain collection using mongodb c# driver
string MNG_REMTNAME = "JOHN";
var collection = mongoDB.GetCollection<EMPLOYEES>("EMPLOYEES");
if (!string.IsNullOrEmpty(MNG_REMTNAME))
{
IMongoQuery MFName = new QueryDocument();
MFName = Query.Or(Query.Matches("MNG_FIRST_NAME", MNG_REMTNAME.ToUpper()),
Query.Matches("MNG_MIDDLE_NAME", MNG_REMTNAME.ToUpper()),
Query.Matches("MNG_LAST_NAME", MNG_REMTNAME.ToUpper()),
Query.ElemMatch("MNG_ALIASIST", Query.Or(Query.Matches("AKAFIRST_NAME",
MNG_REMTNAME.ToUpper())))
);
}
var colln = collection.Find(MFName).ToList();
Please help with some solution to increase the performance.
Change the line
Query.ElemMatch("MNG_ALIASIST", Query.Or(Query.Matches("AKAFIRST_NAME",
MNG_REMTNAME.ToUpper())))
for this one
Query.ElemMatch("MNG_ALIASIST", Query.EQ("AKAFIRST_NAME", MNG_REMTNAME.ToUpper()))
Also have in mind that searching in MongoDB Arrays is very expensive unless you have the proper Indexes. So make sure that you have an index with at least the field MNG_ALIASIST.
Consider creating a Multikey index for this field http://docs.mongodb.org/manual/core/index-multikey/
I have a collection which contains documents like:
{
field1: {subfield1:{ssfield1:5,ssfield2:6},subfield2:6},
field2: 1,
...
}
I'd like to fetch only the subfield, but I'm not sure how to get it querying from csharp (it doesn't seem to return the bsondocument within the bsondocument).
Any help?
I tried this:
String c = "mongodb://"+myip;
MongoServer server = MongoServer.Create(c);
MongoDatabase db = server.GetDatabase(mydb);
var collection = db.GetCollection(col);
string[] fields = new string[] { "field1" };
MongoCursor cursor = collection.Find().SetFields(fields);
but it seems to return
{subfield2:6}
I created a collection with one document very similar to your sample document:
> db.test.find().pretty()
{
"_id" : ObjectId("518ac1aa92f1c388279a9979"),
"field1" : {
"subfield1" : {
"ssfield1" : 5,
"ssfield2" : 6
},
"subfield2" : 6
},
"field2" : 1
}
>
Before showing the result I got when I attempted to reproduce your C# code, let's look at the same query in the MongoDB shell:
> db.test.find({}, { field1 : 1 }).pretty()
{
"_id" : ObjectId("518ac1aa92f1c388279a9979"),
"field1" : {
"subfield1" : {
"ssfield1" : 5,
"ssfield2" : 6
},
"subfield2" : 6
}
}
>
There are several things to notice here:
By default the server always returns the _id field
field1 was the only other field returned (just what we asked for)
subfield2 was returned because it's embedded in field1
I used slightly different C# code from yours to test:
foreach (var document in collection.FindAll().SetFields("field1"))
{
Console.WriteLine(document.ToJson(new JsonWriterSettings { Indent = true }));
}
And the output I got from that loop was:
{
"_id" : ObjectId("518ac1aa92f1c388279a9979"),
"field1" : {
"subfield1" : {
"ssfield1" : 5.0,
"ssfield2" : 6.0
},
"subfield2" : 6.0
}
}
which is essentially identical to the output from the MongoDB shell.
Let me know if you have any further questions.
In MongoDB, if I have a document structure as follows:
{ "_id" : { "$binary" : "jchPoPd7PUS1w+sR7is23w==", "$type" : "03" },
"companies" :
[
{ "_id" : { "$binary" : "jchPoPd7PUS1w+sR7is23w==", "$type" : "03" },
"name" : "Google" },
{ "_id" : { "$binary" : "jchPoPd7PUS1w+sR7is23w==", "$type" : "03" },
"name" : "Greenfin" },
{ "_id" : { "$binary" : "jchPoPd7PUS1w+sR7is23w==", "$type" : "03" },
"name" : "Zynet" }
],
"firstname" : "Peter",
"surname" : "Smith" }
(i.e. a Person document with a Companies array embedded within the person document), then how do I update ALL occurrences of a specific Company (targetting via the company _id) with a single query+update?
I have tried the following:
MongoCollection personCollection = mdb.GetCollection("person");
BsonBinaryData bin = new BsonBinaryData(new Guid("0AE91D6B-A8FA-4D0D-A94A-91D6AC9EE343"));
QueryComplete query = Query.EQ("companies._id", bin);
var update = Update.Set("companies.name", "GreenfinNewName");
SafeModeResult result = personCollection.Update(query, update, UpdateFlags.Multi);
but it doesn't work. I guess my question boils down to two questions: how do I target the embedded companies in the initial query, and then how do I set the new company name in the Set statement. Note: In this example I have chosen to "denormalise" the company data, and embed it in each person document, so there may be several person documents with the same company id and name. Thanks very much.
UPDATE:
Using Bugai13's technique I've got closer. This works:
MongoCollection personCollection = mdb.GetCollection("person");
QueryComplete query = Query.EQ("companies.name", "Bluefin");
var update = Update.Set("companies.$.companynotes", "companynotes update via name worked");
SafeModeResult result = personCollection.Update(query, update, UpdateFlags.Multi, SafeMode.True);
But this doesn't work:
MongoCollection personCollection = mdb.GetCollection("person");
BsonBinaryData bin = new BsonBinaryData(new Guid("0AE91D6B-A8FA-4D0D-A94A-91D6AC9EE343"));
Builders.QueryComplete query = Query.EQ("companies._id", bin);
var update = Update.Set("companies.$.companynotes", "companynotes update via id worked");
SafeModeResult result = personCollection.Update(query, update, UpdateFlags.Multi, SafeMode.True);
So, I can't yet update using the primary key, which is what I need to do...
I suppose use you should take a look into positional operator in mongodb:
var update = MongoDB.Driver.Builders.Update
.Set("companies.$.name", "GreenfinNewName");
^^
all magic here
Note: above code will update only first matched item in array. So if you have two company in nested array with name = GreenfinNewName above code will update only first matched.
Note: UpdateFlags.Multi means multiple documents, but not multiple items in nested array.
Update:
QueryComplete query = Query.EQ("companies._id",
BsonValue.Create(new Guid("0AE91D6B-A8FA-4D0D-A94A-91D6AC9EE343")));
var update = Update.Set("companies.$.companynotes", "companynotes");
personCollection.Update(query, update, UpdateFlags.Multi, SafeMode.True);
Hope this help!
Just wanted to say thanks to you both. Am learning Mongo and this thread helped.
I'm using the 10gen C# driver, and for reference this is my code:
MongoServer mongo = MongoServer.Create();
MongoDatabase db = mongo.GetDatabase("test");
MongoCollection<BsonDocument> coll = db["contacts"];
BsonDocument doc = new BsonDocument();
doc["FirstName"] = "Daniel";
doc["LastName"] = "Smith";
doc["Address"] = "999 Letsby Avenue";
doc["City"] = "London";
doc["County"] = "Greater London";
doc["Postcode"] = "N13";
coll.Insert<BsonDocument>(doc);
QueryComplete qSel = Query.EQ("Postcode", "N13");
MongoCursor<BsonDocument> cur = coll.Find(qSel);
foreach (BsonDocument bdoc in cur)
{
Console.WriteLine(bdoc["FirstName"] + ":" + bdoc["Address"]);
}
UpdateBuilder docTwo = Update.Set("Postcode", "MK10");
coll.Update(qSel, docTwo, UpdateFlags.Multi);
QueryDocument qSel2 = new QueryDocument("FirstName", "Daniel");
MongoCursor<BsonDocument> cur2 = coll.Find(qSel2);
foreach (BsonDocument bsdoc in cur2)
{
Console.WriteLine(bsdoc["FirstName"] + " : " + bsdoc["Postcode"]);
}