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

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.

Related

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,
},
]
},
]

NetSuite Web API - How to return/populate customFieldList array for Sales Order from a joined search?

I am currently performing a SuiteTalk search via C# that joins multiple tables, one of which is for Sales Orders. When performing a typical GET on a SalesOrder record, the property customFieldList gets populated with an array of transaction custom fields/etc. I am curious how to get the same when doing a search like:
SearchResult searchResult = Client.Service.search(new TransactionSearchAdvanced()
{
criteria = new TransactionSearch()
{
basic = new TransactionSearchBasic()
{
type = new SearchEnumMultiSelectField()
{
#operator = SearchEnumMultiSelectFieldOperator.anyOf,
operatorSpecified = true,
searchValue = new String[] { "_salesOrder" },
},
lastModifiedDate = new SearchDateField()
{
#operator = SearchDateFieldOperator.after,
operatorSpecified = true,
searchValue = fromLastModifiedDateTime.ToUniversalTime(),
searchValueSpecified = true
}
},
},
columns = new TransactionSearchRow()
{
basic = new TransactionSearchRowBasic()
{
internalId = new SearchColumnSelectField[] { new SearchColumnSelectField() },
tranId = new SearchColumnStringField[] { new SearchColumnStringField() },
tranDate = new SearchColumnDateField[] { new SearchColumnDateField() },
dateCreated = new SearchColumnDateField[] { new SearchColumnDateField() },
item = new SearchColumnSelectField[] { new SearchColumnSelectField() },
quantity = new SearchColumnDoubleField[] { new SearchColumnDoubleField() },
lastModifiedDate = new SearchColumnDateField[] { new SearchColumnDateField() },
email = new SearchColumnStringField[] { new SearchColumnStringField() },
//customFieldList = new SearchColumnCustomField[] { },
},
itemJoin = new ItemSearchRowBasic()
{
itemId = new SearchColumnStringField[] { new SearchColumnStringField() },
type = new SearchColumnEnumSelectField[] { new SearchColumnEnumSelectField() },
},
customerJoin = new CustomerSearchRowBasic()
{
internalId = new SearchColumnSelectField[] { new SearchColumnSelectField() },
billAddress = new SearchColumnStringField[] { new SearchColumnStringField() },
companyName = new SearchColumnStringField[] { new SearchColumnStringField() },
phone = new SearchColumnStringField[] { new SearchColumnStringField() },
email = new SearchColumnStringField[] { new SearchColumnStringField() },
},
customSearchJoin = new CustomSearchRowBasic[]
{
},
}
});
The property I want populated is commented out within the TransactionSearchRowBasic object:
//customFieldList = new SearchColumnCustomField[] { },
Any ideas? Thank you in advance!
The search operation doesn't return as much information as a GET operation does on the SuiteTalk Web Services.
For each record that is returned in your SearchResult, use the internalId or document number to GET that record. This should then include your custom fields.
NetSuiteService _service = new NetSuiteService();
ReadResponse res = _service.get(new RecordRef { internalId = internalID, type = RecordType.salesOrder, typeSpecified = true });

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 } });

parsing json with using json.net linq

I tray to parse json with using Json.Net but i am new parsing json and i didn't get good result after so many test.
json structure is as below;
[
{
"Coo":{
"id":"1"
},
"Hor":{
"name":"Poo"
},
"Vor":{
"name":"Soo"
},
"Status":"1",
"Tola":[
{
"value":"10",
},
{
"value":"20",
}
],
"Opt":[
]
},
{
"Coo":{
"id":"2"
},
"Hor":{
"name":"Zoo"
},
"Vor":{
"name":"Koo"
},
"Status":"2",
"Tola":[
{
"value":"20",
},
{
"value":"10",
}
],
"Opt":[
]
},
{
"Coo":{
"id":"3"
},
"Hor":{
"name":"Moo"
},
"Vor":{
"name":"Noo"
},
"Status":"1",
"Tola":[
{
"value":"30",
},
{
"value":"20",
}
],
"Opt":[
]
}
]
My code is as below for parsing.
_JsonString = _JsonString.Trim().Trim('[',']');
JObject _JObject = JObject.Parse(_JsonString);
var _JItems = _JObject.SelectToken(".")
.Select(s => new
{
_Id = (string)s.SelectToken("Coo.id"),
_WhereClause = (string)s.SelectToken("Status")
})
.Where(w => w._WhereClause == "1");
foreach (var _JItem in _JItems)
{
MessageBox.Show(_JItem._Id.ToString());
}
Thank you in advance.
You are using JObject while you should use JArray:
Remove this line:
_JsonString = _JsonString.Trim().Trim('[', ']'); /*removed*/
And change
JObject _JObject = JObject.Parse(_JsonString);
To
JArray _JObject = JArray.Parse(_JsonString);
Full code:
JArray _JObject = JArray.Parse(_JsonString);
var _JItems = _JObject.SelectToken(".")
.Select(s => new
{
_Id = (string)s.SelectToken("Coo.id"),
_WhereClause = (string)s.SelectToken("Status")
})
.Where(w => w._WhereClause == "1");
foreach (var _JItem in _JItems)
{
MessageBox.Show(_JItem._Id.ToString());
}

Categories