InsertMany Document in a MongoDB Collection using C# BsonArray - c#

How to Insert more than one document in a Single statement using InsertMany() MongoDB Method in C#
My MongoDB Database and Connections
IMongoClient _client;
IMongoDatabase _database;
_client = new MongoClient();
_database = _client.GetDatabase("test");
var collection = _database.GetCollection<BsonDocument>("EmpInfo");
I'm having a Collection - BsonArray
var EmpInfoArray = new BsonArray {
new BsonDocument
{
{"EmpID", "100"},
{"EmpName", "John"},
{"EmpMobile", new BsonArray
{
new BsonDocument {
{"MobNumber", "55566610"},
{"IsPreferred", true},
{"IsLive", false}
},
new BsonDocument {
{"MobNumber", "55566611"},
{"IsPreferred", true},
{"IsLive", true}
},
}
},
{"IsLive", true}
},
new BsonDocument
{
{"EmpID", "101"},
{"EmpName", "Peter"},
{"EmpMobile", new BsonArray
{
new BsonDocument {
{"MobNumber", "55566610"},
{"IsPreferred", true},
{"IsLive", false}
},
new BsonDocument {
{"MobNumber", "55566611"},
{"IsPreferred", true},
{"IsLive", false}
},
}
},
{"IsLive", true}
},
new BsonDocument
{
{"EmpID", "102"},
{"EmpName", "Jack"},
{"EmpMobile", new BsonArray
{
new BsonDocument {
{"MobNumber", "55566610"},
{"IsPreferred", true},
{"IsLive", true}
},
new BsonDocument {
{"MobNumber", "55566611"},
{"IsPreferred", true},
{"IsLive", true}
},
}
},
{"IsLive", false}
}
}
The Insert Statement:
collection.InsertMany(EmpInfoArray);
In the above InsertMany() Extended method has a build error. Kindly assist me how to insert multiple records in a single statement execution using C#.

Off the top of my head, the build error is most probably because the InsertMany method is expecting a collection (IEnumerable,List or Array..) of BsonDocument instead of a BsonArray.
try :
var EmpInfoArray = new List<BsonDocument>() { //Changed BsonArray to List<BsonDocument>
new BsonDocument
{
{"EmpID", "100"},
{"EmpName", "John"},
{"EmpMobile", new BsonArray
.
.
.

Related

Filter $gte and $lte a string in C#

how to add filter with $gte and $lte a string value? I have a StaredAt but is a string type. How to filter in a range, for example:
Range: 2022-02-02 / 2022-02-04
I tried this but throw and exception:
var subfilter = new BsonDocument("$expr",
new BsonDocument("$gte",
new BsonArray {
new BsonDocument("$toDate", "$StartDate"),
From
}
)
);
var subfilterTo = new BsonDocument("$expr",
new BsonDocument("$lte",
new BsonArray {
new BsonDocument("$toDate", "$StartDate"),
To
}
)
);
The exception is:
MongoDB.Driver.MongoCommandException: Command find failed: An object representing an expression must have exactly one field: { $gte: [ { $toDate: "$StartDate" }, new Date(1663124400000) ], $lte: [ { $toDate: "$StartDate" }, new Date(1663210799000) ] }
I would recommend using the C# Mongodb Linq provider.
That way you can avoid the nesting of the BsonDocuments and it can be as simple as:
collection.AsQueryable().Where(x => x.From > StartDate && x.To < EndDate)
In order to use $expr to convert the strings to dates, you can create a single expression with a AND condition that combines both conditions:
new BsonDocument("$expr", new BsonDocument("$and", new BsonArray
{
new BsonDocument("$gte",
new BsonArray
{
new BsonDocument("$toDate", "$StartDate"),
From
}),
new BsonDocument("$lte",
new BsonArray
{
new BsonDocument("$toDate", "$StartDate"),
To
})
}));
This is equivalent to the following query:
{
$expr: {
$and: [
{ $gte: [{ $toDate: "$StartDate" }, From] },
{ $lte: [{ $toDate: "$StartDate" }, To] },
];
}
}
As a sidenote: if you convert the dates from string to date data types in the documents, this simplifies the query and will improve query performance because you can use an index.

query in mongodb Driver c# for getting Last Array Element in each I am Applying Groupy on Activity Type and I want last array element in each

var group = new BsonDocument
{
{
"_id", new BsonDocument {
{"ActivityType", "$ActivityType"},
}
},
// {
// "Result", new BsonDocument("$push", new BsonDocument
// {
// // { "$slice",-1},
// { "SessionRecords", "$SessionRecords" },
// }
// )
//},
{
"Result", new BsonDocument("$push", new BsonDocument(
"$slice", new BsonArray
{
//new BsonDocument("$slice",new BsonDocument("SessionRecords","$SessionRecords")),
new BsonArray().Add("$SessionRecords.TemplateId"),
-1,
}
))
}
};
this is my query and may data is like this
it return all array elements data is like
[
{
"_id": "62f110c25a1c144e4b4a00ec",
"ActivityType":"Working",
"SessionRecords": [{
"TemplateId": "6229dded08714fdbcdf1c969",
"SecondsCounter": 0,
"BreathCounter": 0,
},
{
"TemplateId": "6229dded08714fdbcdf1c969",
"SecondsCounter": 0,
"BreathCounter": 0,
},
]
},
]

$Cond and $Eq Inside $Project - C# Driver MongoDB

Im facing a litle problem in Deserializing BsonDocuments type, I couldn't find the reason, but I have some clues, maybe, it's about {0 fields}, because the error tel me about the column I have {0 fields}. I also realised that its a {} (empty array).
MY MONGO QUERY ON ROBO 3T AND THE RESULT
MY C# MONGO QUERY
var connString = "mongodb+srv";
var client = new MongoClient(connString);
var database = client.GetDatabase("Base");
var collection = database.GetCollection<BsonDocument>("collection");
var match1 = new BsonDocument("$match", new BsonDocument("PartnerId", "2021"));
var match2 = new BsonDocument("$match", new BsonDocument("CD_CLIENTE", codCond));
var project = new BsonDocument { { "$project", new BsonDocument { { "_id", 0 }, { "CD_CLIENTE", 1 }, { "CD_ACESSO", 1 },
{ "ID_ACESSO", 1 },{ "NOME", 1 },{ "NU_TELEFONE", 1 }, { "EMAIL", 1 }, { "NU_KIPER_RF", 1 }, { "NU_KIPER_TAG", 1 },
{ "FG_KIPER_MOBILE", 1 },{ "KEY_HASH", 1 },}}}; MY MONGO AND RESULT
var sort = new BsonDocument("$sort", new BsonDocument("NOME", 1));
var pipeline = new[] { match1, match2, project, sort };
var result = collection.Aggregate<BsonDocument>(pipeline).ToList();
var lista = JsonConvert.DeserializeObject<List<UsuariosAcessos>>(result.ToJson());
The error is here:
var lista = JsonConvert.DeserializeObject<List<UsuariosAcessos>>(result.ToJson());
Exatly when I try to Deserialise an that "empty array" to Model int?. I found a work around, because I just need to know if, we have or dont not something in NU_KIPER_TAG and NU_KIPER_RF, so, I did this new Mongo query.
NEW MONGO QUERY USING $COND
db.dbACESSO.aggregate([
{
$match: { PartnerId: "2021", CD_CLIENTE: 4003}
},
{
$project: {_id:0, CD_CLIENTE:1, CD_ACESSO:1, ID_ACESSO:1, NOME:1, NU_TELEFONE:1,EMAIL:1, FG_KIPER_MOBILE:1,
TAG:{$cond: [{ $eq: [ "$NU_KIPER_TAG", {}]}, 0, 1 ]}, CONTROLE:{$cond: [{ $eq: [ "$NU_KIPER_RF", {}]}, 0, 1 ]},
APPATIVO:{$cond: [{ $eq: [ "$KEY_HASH", {}]}, "", "$KEY_HASH" ]}}
}
])
I couldnt translate it to C#, I tried hard, but i'm not familiarized with the sintaxe. I also googled for a sample with no success.
I think its something like:
var project = new BsonDocument {
{
"$project", new BsonDocument { { "_id", 0 }, { "CD_CLIENTE", 1 }, { "CD_ACESSO", 1 },{ "ID_ACESSO", 1 },{ "NOME", 1 }
,{ "NU_TELEFONE", 1 }, { "EMAIL", 1 }, { "NU_KIPER_RF", 1 }, { "NU_KIPER_TAG", 1 },{ "FG_KIPER_MOBILE", 1 },{ "KEY_HASH", 1 },
{"TAG", new BsonDocument{{"$cond", new BsonDocument {{ "$eq", "$NU_KIPER_TAG", "{}"}}, 0, 1 ]}, } }
}
}
};
Try this way, it will work!
var project = new BsonDocument
{
{
"$project", new BsonDocument
{
{ "_id", 0},
{ "CD_CLIENTE", 1},
{ "CD_ACESSO", 1 },
{ "NOME", 1},
{ "EMAIL", 1 },
{ "FG_KIPER_MOBILE", 1 },
{ "GRUPO", "$GRUPO.NM_DESCRICAO" },
{ "UNIDADE", "$UNIDADE.NM_DESCRICAO" },
{ "NU_TELEFONE", new BsonDocument{{ "$cond", new BsonArray{new BsonDocument{{"$eq", new BsonArray{ "$NU_TELEFONE", new BsonDocument { } } }}, "","$NU_TELEFONE" } }}},
{ "TAG", new BsonDocument{{ "$cond", new BsonArray{new BsonDocument{{"$eq", new BsonArray{ "$NU_KIPER_TAG", new BsonDocument { } } }}, 0,1 } }}},
{ "CONTROLE", new BsonDocument{{ "$cond", new BsonArray{new BsonDocument{{"$eq", new BsonArray{ "$NU_KIPER_RF", new BsonDocument { } } }}, 0,1 } }}},
{ "APPATIVO", new BsonDocument{{ "$cond", new BsonArray{new BsonDocument{{"$eq", new BsonArray{ "$KEY_HASH", new BsonDocument { } } }}, "", "$KEY_HASH" } }}},
}
}
};
The empty array will be represented for: new BsonDocument { }
{ "NU_TELEFONE", new BsonDocument{{ "$cond", new BsonArray{new BsonDocument{{"$eq", new BsonArray{ "$NU_TELEFONE", new BsonDocument { } } }}, "","$NU_TELEFONE" } }}},
What about using the fluent C# like this:
var connString = "mongodb+srv";
var client = new MongoClient(connString);
var database = client.GetDatabase("Base");
var collection = database.GetCollection<UsuariosAcessos>("collection"); //Here you put you Model
var filter = Builders<UsuariosAcessos>.Filter.Eq(x => x.PartnerId, cliente)
& Builders<UsuariosAcessos>.Filter.Eq(x => x.CD_CLIENTE, codCond);
var lista = collection.Aggregate().Match(filter).Project(x => new UsuariosAcessos
{
CD_CLIENTE = x.CD_CLIENTE,
ID_ACESSO = x.ID_ACESSO,
CD_ACESSO = x.CD_ACESSO,
NOME = x.NOME,
NU_TELEFONE = x.NU_TELEFONE,
EMAIL = x.EMAIL,
NU_KIPER_RF = x.NU_KIPER_RF,
NU_KIPER_TAG = x.NU_KIPER_TAG,
FG_KIPER_MOBILE = x.FG_KIPER_MOBILE,
KEY_HASH = x.KEY_HASH
}).ToList();
About your problem at Deserialization time, I think it's not possible to translate {} (empty array) to int or int?, it's appear to be the reason your deserialization is not working, try to change your model.
FROM:
public int? NU_KIPER_TAG { get; set; }
public int? NU_KIPER_RF { get; set; }
TO:
public object NU_KIPER_TAG { get; set; }
public object NU_KIPER_RF { get; set; }
Its not you are looking for, but, maybe your Deserialization are going to Work. After that, you can convert the data. Hope this helps.

BSON error creating new BsonDocument for MongoDB

I'm new to MongoDB and, after some tutorials, I'm trying to read data from my SQL Server database and reverse them in MongoDB, with C# and Entity Framework.
I found this code on MongoDB site:
async static void addDoc()
{
var document = new BsonDocument
{
{ "address" , new BsonDocument
{
{ "street", "2 Avenue" },
{ "zipcode", "10075" },
{ "building", "1480" },
{ "coord", new BsonArray { 73.9557413, 40.7720266 } }
}
},
{ "borough", "Manhattan" },
{ "cuisine", "Italian" },
{ "grades", new BsonArray
{
new BsonDocument
{
{ "date", new DateTime(2014, 10, 1, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "A" },
{ "score", 11 }
},
new BsonDocument
{
{ "date", new DateTime(2014, 1, 6, 0, 0, 0, DateTimeKind.Utc) },
{ "grade", "B" },
{ "score", 17 }
}
}
},
{ "name", "Vella" },
{ "restaurant_id", "41704620" }
};
var collection = _database.GetCollection<BsonDocument>("restaurants");
await collection.InsertOneAsync(document);
}
It works as I expect. So, I made this:
using (var db = new Entities())
{
foreach (var trans in db.TRANSACTIONS)
{
try
{
var document = new BsonDocument
{
{ "ID", erog.ID.ToBson() },
{ "CUSTOMER" , new BsonDocument
{
{ "CSTID", trans.CUSTOMERS.CSTID.ToBson() },
{ "NAME", trans.CUSTOMERS.NAME.ToBson()},
{ "CITY", trans.CUSTOMERS.CITY.ToBson() },
{ "ZIP", trans.CUSTOMERS.ZIP.ToBson() },
{ "STATE", trans.CUSTOMERS.STATE.ToBson() },
}
},
{ "TRANSACTIONNUMBER", trans.TRANSACTIONNUMBER.ToBson() },
{ "TIMESTAMP", erog.TIMESTAMP.ToBson() },
{ "AMOUNT", erog.AMOUNT.ToBson() },
{ "PAYMENT", erog.PAYMENT.ToBson() },
};
var collection = _database.GetCollection<BsonDocument>("transactions");
collection.InsertOne(document);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
When I try to execute this code, I get an error when executing var document = new BsonDocument {....}; the error is "A string value cannot be written to the root level of a bson document". So, as you can see, I tried to put the .ToBson() at the end of my values, but the result is still the same.
The only difference is the value isn't a string between two quotation marks, but it is a real value from my table.
How can I reach my goal and create&insert a document in my MongoDB database, starting from my code above?
Ok, dumb question, dumb solution.
Just replace all toBson() with toString() and now it works! :)

How to Convert db.runcomand to c#.net MongoDB

How to convert this command for c# .net?
db.logs.aggregate([
{
$geoNear: {
near: { type: "Point", coordinates: [ lng , lat ] },
distanceField: "dist.distance",
maxDistance: 5,
includeLocs: "dist.location",
num: 1000,
spherical: true
},
}
])
Finally, It's work fine.
BsonDocument geoPoint = new BsonDocument
{
{"type","Point"},
{"coordinates",new BsonArray(new Double[]{double.Parse(lon), double.Parse(lat)})}
};
BsonDocument query = new BsonDocument
{
{
"$eq", new BsonArray {"City", "Bangkok" }
}
};
BsonDocument geoNearOptions = new BsonDocument
{
{"spherical", true},
{"limit", 10000}, //need to test to see what limit is appropriate, should we do a filter first?
{"maxDistance", 400},
{"query",filter},
{"near",geoPoint},
{"distanceField","dist.distance"},
{"includeLocs", "dist.location"},
};
var stage = new BsonDocumentPipelineStageDefinition<BsonDocument, BsonDocument>(new BsonDocument { { "$geoNear", geoNearOptions } });
var colAggregate = collection2.Aggregate().AppendStage(stage).Sort(new BsonDocument { { "_id", 1 } });

Categories