How to flatten sub-documents in mongo db - json

My collection has document like this
{
"_id" : ObjectId("587c8d0364b6e32706f7edef"),
"first_name" : "John",
"last_name" : "Doe",
"password" : "aasdjsabb12213b21bbcghc1h2",
"shift" : "A",
"dept" : "Management"
"Requests" : [
{
"weekId" : 1,
"MO" : 1,
"TU" : 2,
"W" : 3,
"TH" : 9,
"FR" : 10,
"SA" : 6,
"SU" : 1
}
]
}
I want to export the result of my query to csv and need fields flattened out like this
{
"_id" : ObjectId("587c8d0364b6e32706f7edef"),
"first_name" : "John",
"last_name" : "Doe",
"password" : "aasdjsabb12213b21bbcghc1h2",
"shift" : "A",
"dept" : "Management"
"weekId" : 1,
"MO" : 1,
"TU" : 2,
"W" : 3,
"TH" : 9,
"FR" : 10,
"SA" : 6,
"SU" : 1
}
I am trying to use aggregate function but to no avail. Can anyone suggest me how to do this?
This is my working code but I don't think this is the right way
db.req.aggregate([{$unwind:'$Requests'},{$project: {first_name:1,last_name:1,dept:1,"WeekId":"$Requests.weekdId","Mon":"$Requests.MO","Tue":"$Requests.TU","Wed":"$Requests.W","Thu":"$Requests.TH","Fri":"$Requests.FR","Sat":"$Requests.SA","Sun":"$Requests.SU"}},{$out:"results"}]);

You can do this with an aggregate query, but its not very pretty:
db.test.aggregate([
{$unwind:"$Requests"},
{$project:
{_id:1,
first_name:1,
last_name:1,
password:1,
shift:1,
dept:1,
weekId:"$Requests.weekId",
MO:"$Requests.MO",
TU:"$Requests.TU",
W:"$Requests.W",
TH:"$Requests.TH",
FR:"$Requests.FR",
SA:"$Requests.SA",
SU:"$Requests.SU"}}])
.pretty()
So basically unwind the Requests array, then project out the document you want to produce. Hope this makes sense.

Related

Jmeter: Extracting JSON response with special/spaces characters

Hello can someone help me extract the value of user parameter which is "testuser1"
I tried to use this JSON Path expression $..data I was able to extract the entire response but unable to extract user parameter. Thanks in advance
{
"data": "{ "took" : 13, "timed_out" : false, "_shards" : { "total" : 5, "successful" : 5, "skipped" : 0, "failed" : 0 }, "hits" : { "total" : 1, "max_score" : 1.0, "hits" : [ { "_index" : "bushidodb_history_network_eval_ea9656ef-0a9b-474b-8026-2f83e2eb9df1_2021-april-10", "_type" : "network", "_id" : "6e2e58be-0ccf-3fb4-8239-1d4f2af322e21618059082000", "_score" : 1.0, "_source" : { "misMatches" : [ "protocol", "state", "command" ], "instance" : "e3032804-4b6d-3735-ac22-c827950395b4|0.0.0.0|10.179.155.155|53|UDP", "protocol" : "UDP", "localAddress" : "0.0.0.0", "localPort" : "12345", "foreignAddress" : "10.179.155.155", "foreignPort" : "53", "command" : "ping yahoo.com ", "user" : "testuser1", "pid" : "10060", "state" : "OUTGOINGFQ", "rate" : 216.0, "originalLocalAddress" : "192.168.100.229", "exe" : "/bin/ping", "md5" : "f9ad63ce8592af407a7be43b7d5de075", "dir" : "", "agentId" : "abcd-dcd123", "year" : "2021", "month" : "APRIL", "day" : "10", "hour" : "12", "time" : "1618059082000", "isMerged" : false, "timestamp" : "Apr 10, 2021 12:51:22 PM", "metricKey" : "6e2e58be-0ccf-3fb4-8239-1d4f2af322e2", "isCompliant" : false }, "sort" : [ 1618059082000 ] } ] }, "aggregations" : { "count_over_time" : { "buckets" : [ { "key_as_string" : "2021-04-10T08:00:00.000-0400", "key" : 1618056000000, "doc_count" : 1 } ] } }}",
"success": true,
"message": {
"code": "S",
"message": "Get Eval results Count Success"
}
}
Actual Response:
Images
What you posted doesn't look like a valid JSON to me.
If in reality you're getting what's in your image, to wit:
{
"data": "{ \"took\" : 13, \"timed_out\" : false, \"_shards\" : { \"total\" : 5, \"successful\" : 5, \"skipped\" : 0, \"failed\" : 0 }, \"hits\" : { \"total\" : 1, \"max_score\" : 1.0, \"hits\" : [ { \"_index\" : \"bushidodb_history_network_eval_ea9656ef-0a9b-474b-8026-2f83e2eb9df1_2021-april-10\", \"_type\" : \"network\", \"_id\" : \"6e2e58be-0ccf-3fb4-8239-1d4f2af322e21618059082000\", \"_score\" : 1.0, \"_source\" : { \"misMatches\" : [ \"protocol\", \"state\", \"command\" ], \"instance\" : \"e3032804-4b6d-3735-ac22-c827950395b4|0.0.0.0|10.179.155.155|53|UDP\", \"protocol\" : \"UDP\", \"localAddress\" : \"0.0.0.0\", \"localPort\" : \"12345\", \"foreignAddress\" : \"10.179.155.155\", \"foreignPort\" : \"53\", \"command\" : \"pingyahoo.com\", \"user\" : \"testuser1\", \"pid\" : \"10060\", \"state\" : \"OUTGOINGFQ\", \"rate\" : 216.0, \"originalLocalAddress\" : \"192.168.100.229\", \"exe\" : \"/bin/ping\", \"md5\" : \"f9ad63ce8592af407a7be43b7d5de075\", \"dir\" : \"\", \"agentId\" : \"abcd-dcd123\", \"year\" : \"2021\", \"month\" : \"APRIL\", \"day\" : \"10\", \"hour\" : \"12\", \"time\" : \"1618059082000\", \"isMerged\" : false, \"timestamp\" : \"Apr10, 202112: 51: 22PM\", \"metricKey\" : \"6e2e58be-0ccf-3fb4-8239-1d4f2af322e2\", \"isCompliant\" : false }, \"sort\" : [ 1618059082000 ] } ] }, \"aggregations\" : { \"count_over_time\" : { \"buckets\" : [ { \"key_as_string\" : \"2021-04-10T08: 00: 00.000-0400\", \"key\" : 1618056000000, \"doc_count\" : 1 } ] } }}",
"success": true,
"message": {
"code": "S",
"message": "Get Eval results Count Success"
}
}
the easiest way is just using 2 JSON Extractors:
Extract data attribute value into a JMeter Variable from the response
Extract user attribute value into a JMeter variable from ${data} JMeter Variable:
Demo:
If the response looks like exactly you posted you won't be able to use JSON Extractors and will have to treat it as normal text so your choice is limited to Regular Expression Extractor, example regular expression:
"user"\s*:\s*"(\w+)"
Add Regular Expression extractor with the corresponding request and extract it. Use the below expression.
Expression: "user" : "(.*?)"
Ref: https://jmeter.apache.org/usermanual/regular_expressions.html
Regular Expression Extractor Sample

Extract JSON value using Jmeter

I have this JSON:
{
"totalMemory" : 12206567424,
"totalProcessors" : 4,
"version" : "0.4.1",
"agent" : {
"reconnectRetrySec" : 5,
"agentName" : "1001",
"checkRecovery" : false,
"backPressure" : 10000,
"throttler" : 100
},
"logPath" : "/eq/equalum/eqagent-0.4.1.0-SNAPSHOT/logs",
"startTime" : 1494837249902,
"status" : {
"current" : "active",
"currentMessage" : null,
"previous" : "pending",
"previousMessage" : "Recovery:Starting pipelines"
},
"autoStart" : false,
"recovery" : {
"agentName" : "1001",
"partitionInfo" : { },
"topicToInitialCapturePosition" : { }
},
"sources" : [ {
"dataSource" : "oracle",
"name" : "oracle_source",
"captureType" : "directOverApi",
"streams" : [ ],
"idlePollingFreqMs" : 100,
"status" : {
"current" : "active",
"currentMessage" : null,
"previous" : "pending",
"previousMessage" : "Trying to init storage"
},
"host" : "192.168.191.5",
"metricsType" : { },
"bulkSize" : 10000,
"user" : "STACK",
"password" : "********",
"port" : 1521,
"service" : "equalum",
"heartbeatPeriodInMillis" : 1000,
"lagObjective" : 1,
"dataSource" : "oracle"
} ],
"upTime" : "157 min, 0 sec",
"build" : "0-SNAPSHOT",
"target" : {
"targetType" : "equalum",
"agentID" : 1001,
"engineServers" : "192.168.56.100:9000",
"kafkaOptions" : null,
"eventsServers" : "192.168.56.100:9999",
"jaasConfigurationPath" : null,
"securityProtocol" : "PLAINTEXT",
"stateMonitorTopic" : "_state_change",
"targetType" : "equalum",
"status" : {
"current" : "active",
"currentMessage" : null,
"previous" : "pending",
"previousMessage" : "Recovery:Starting pipelines"
},
"serializationFormat" : "avroBinary"
}
}
I trying using Jmeter to extract out the value of agentID, how can I do that using Jmeter, what would be better ? using extractor or json extractor?
what I am trying to do is to extract agentID value in order to use it on another http request sample, but first I have to extract it from this request.
thanks!
I believe using JSON Extractor is the best way to get this agentID value, the relevant JsonPath query will be as simple as $..agentID
Demo:
See the following reference material:
JsonPath - Getting Started - for initial information regarding JsonPath language, functions, operators, etc.
JMeter's JSON Path Extractor Plugin - Advanced Usage Scenarios - for more complex scenarios.

How to push new key and value in JSON array in mongodb?

How can I push new key and value in JSON array?
I tried I used push keyword in update query but I got a different output. I used:
db.users.updateOne({"name":"viki"},{$push{"address.district":"thambaram"}})
I have this document:
{ "_id" : ObjectId("58934f10c7592b1494fd9a4d"), "name" : "viki", "age" : 100, "subject" : [ "c", "node.js", "java" ], "address" : { "city" : "chennai", "state" : "tamilnadu", "pincode" : "123" } }
I want to add "district":"thambaram" in address json array
I need like:
{ "_id" : ObjectId("58934f10c7592b1494fd9a4d"), "name" : "viki", "age" : 100, "subject" : [ "c", "node.js", "java" ], "address" : { "city" : "chennai", "state" : "tamilnadu", "pincode" : "123","district":"thambaram"} }
Use $set
db.users.updateOne({"name":"viki"},{$set:{"address.district":"thambaram"}})
This should work.
The $push operator appends a specified value to an array. In your case you should use $set

F# - Compare 2 JsonValue'

I have 2 Json values that are similar, but there are some differences.
Json1:
{
"id": "1",
"people" : [
{
"Id" : 1421,
"Name" : "Jackson",
"Age" : 21,
"Status" : "Available"
},
{
"Id" : 5916,
"Name" : "Steven",
"Age" : 22,
"Status" : "Available"
}
],
"totalRecords" : 2
}
Json2:
{
"id": "1",
"people" : [
{
"Id" : 1421,
"Name" : "Jackson",
"Age" : 21,
"Status" : "Available"
},
{
"Id" : 5916,
"Name" : "Steven",
"Age" : 22,
"Status" : "Unavailable"
},
{
"Id" : 1337,
"Name" : "Alice",
"Age" : 19,
"Status" : "Available"
}
],
"totalRecords" : 3
}
I'd like to know if there's a way to compare the two Jsonvalues. At the moment I de-serialize the data into a type and then use the Id's and the status' to see if anythings changed. I then pick out the parts that are different (In the example it'd be Steven and Alice) and add them to a sequence for later.
I'd like to reverse a few of the steps. I'd like too compare the json, find the differences, deserialize them and then add them to the sequence, or add them to the sequence then de-serialize the whole sequence. Either way, same result.
Any ideas?

MongoDB doesnt give the right result

Problem with mongoDB
I have a collection in my mongodb with the following colums:
{"_id" : ObjectId("5443cddc425e215c7290a179"), "orderid" : 1002854, "customerid" : 45978, "campaignid" : 2141, "orderdate" : "2009-10-13 00:00:00", "city" : "NEWTON", "state" : "MA", "zipcode" : 2459, "paymenttype" : "VI", "totalprice" : 190, "numorderlines" : 3, "numunits" : 3}
There are 239 different campaignid's, which all should have a value of 1, but they all have 0.
Now i want to have per campaignid the total amount of numunits grouped, which i use the following statement:
db.orders.aggregate({$group: {_id: "$campaignid", Numunits: {$sum:" $numunits"}}})
It gives back the following result:
{ "_id" : 2146, "Numunits" : 0} , { "_id" : 2111, "Numunits" : 0} etc...
Now the expected result is:
{ "_id": 2146, "Numunits" : 93} , { "_id" : 2111, "Numunits" : 23} etc..
Mongo doesn't trim space for you if any. Try this:
db.orders.aggregate(
[
{$group: {
_id: "$campaignid",
Numunits: {$sum:"$numunits"}
}
}
])