Unable to print BSON object from javascript - javascript

My mongoDB collection looks like this :
{
"_id" : ObjectId("5070310e0f3350482b00011d"),
"emails" : [
{
"_id" : ObjectId("5070310e0f3350482b000120"),
"_type" : "Email",
"name" : "work",
"email" : "peter.loescher#siemens.com",
"current" : true
}
]
}
and this is the .js code i use to print the contents :
c = db.contacts.findOne( { "emails.email" : { $ne : null } }, { "emails" : 1 } )
print(c._id.toString() + " " + c.emails[0]);
when I try to run this javascript file, it is just displaying the id but not the email array.
output:
5070310e0f3350482b00011d [object bson_object]
but when I try c.emails[0].email is is giving proper result. i.e. peter.loescher#siemens.com
All I need is I want to display the whole emails embedded object.
i.e.
"emails" : [
{
"_id" : ObjectId("5070310e0f3350482b000120"),
"_type" : "Email",
"name" : "work",
"email" : "peter.loescher#siemens.com",
"current" : true
}
]
Where I am going wrong?. Any help would be appreciated.

You need printjson to output a nicely formatted JSON:
printjson(c.emails[0]);
Here it is the documentation.

Related

change only one field of entire array of embedded document in mongoose

i have a list schema and a question set schema. the quetsionSet schema is embedded inside the list schema. its working fine but how can i update anything inside the array of embedded document i.e. here i want to change the listname of all the documents inside questionSet (array of questionSet documents).
here is an example of my list document model
{ "_id" : ObjectId("60f2cc07275bbb30d8cb268e"),
"listName" : "dsa",
"aboutList" : "dsa queestions",
questionSet" : [ { "solved" : false,
"_id" : ObjectId("60f2cc12275bbb30d8cb2695"),
"topic" : "array",
"name" : "array is best",
"url" : "www.arr.com",
"listname" : "dsa",
"__v" : 0 },
{ "solved" : false,
"_id" : ObjectId("60f2cc1b275bbb30d8cb269d"),
"topic" : "linked list",
"name" : "reverse list",
"url" : "www.list.com",
"listname" : "dsa",
"__v" : 0 }
],
"__v" : 2
}
you can use the following in your case
db.<collection_name>.updateOne(
{ "_id" : ObjectId("60f2cc07275bbb30d8cb268e")},
{
$set: {
'questionSet.$[].listname': "javascript"
}
}
)

MongoDB - Query nested objects in nested array

I'm kindly requesting your help for this query that I need to do and I'm not very proficient yet in MongoDB. My data structure looks like this:
db.getCollection('EventDateValidation').find({}):
/* 1 */
{
"_id" : ObjectId("5b7b2e3ae5e2100007717d81"),
"_class" : "com.overwatch.common.model.EventDateValidation",
"caseNo" : "OW000002269122201810201135",
"loanNo" : "000002269122",
"eventType" : "BREACLETTR",
"validationStepData" : [
{
"startDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Mahalakshmi M",
"auditedDate" : "2018-12-12"
}
},
{
"completedDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Mahalakshmi M",
"auditedDate" : "2018-12-13"
}
},
{
"deadlineDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Mahalakshmi M",
"auditedDate" : "2018-12-13"
}
}
]
}
/* 2 */
{
"_id" : ObjectId("5b7c11095c2b4d0007bc8c54"),
"_class" : "com.overwatch.common.model.EventDateValidation",
"caseNo" : "OW000000854076201808181158",
"loanNo" : "000000854076",
"eventType" : "FORSALAPPR",
"validationStepData" : [
{
"startDate" : {
"comments" : ""
}
},
{
"completedDate" : {
"comments" : "Received Date = 8/4/2017"
}
},
{
"deadlineDate" : {
"comments" : ""
}
}
]
}
/* 3 */
{
"_id" : ObjectId("5b7ad05d5c2b4d0007bc8631"),
"_class" : "com.overwatch.common.model.EventDateValidation",
"caseNo" : "OW000000873954201810201235",
"loanNo" : "000000873954",
"eventType" : "HUDNOTIFCA",
"validationStepData" : [
{
"startDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Brett Scott",
"auditedDate" : "2018-09-25"
}
},
{
"completedDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Brett Scott",
"auditedDate" : "2018-09-25"
}
},
{
"deadlineDate" : {
"isChecked" : "Y",
"comments" : "",
"auditedBy" : "Brett Scott",
"auditedDate" : "2018-09-25"
}
}
]
}
From this collection, I need to find the documents that have an "auditedDate" in the "deadlineDate". In this example, I would find the documents 1 and 3. Please help me as I'm stuck on this one.
I have tried
db.getCollection('EventDateValidation').find({"validationStepData.deadlineDate.auditedDate":{$exists:true}})
But doesn't seem to work. Help please!
Just for clearing things up: the query in the question works well. I chatted with #Gabriel, and the problem was that Robomongo added hidden non-printable unicode characters to the query.
All in all, for any interested nomads, here are few ways to query an array of objects:
1) Implicit $elemMatch / simple dot notation on an array:
db.getCollection('EventDateValidation').find({"validationStepData.deadlineDate.auditedDate": {$exists:true}})
2) Explicit $elemMatch (we can have multiple query criteria):
db.getCollection('EventDateValidation').find({"validationStepData": { $elemMatch: {"deadlineDate.auditedDate" : {$exists:true} }}})
3) Array dot notation with an index position (when we know the exact position of an element inside an array):
db.getCollection('EventDateValidation').find({"validationStepData.2.deadlineDate.auditedDate": {$exists:true}})
Dot notation wouldn't work since you have an array of objects within validationStepData. You could use $elemMatch to apply your query conditions to the array elements that match your expression.
db.getCollection('EventDateValidation').find({"validationStepData" : { $elemMatch: {"deadlineDate.auditedDate" : {$exists:true} }}})

MongoDB converting from int32 to double itself

I am getting a weird problem when I run in shell for mongoDB.
My collection structure is like below in mongoDB.The type of ServiceList items must be integer.
{
"_id" : ObjectId("56565"),
"Contact" : "",
"Email" : "",
"AppList" : [
{
"Code" : "",
"Usage" : NumberInt(542),
"LicenceType" : "Monthly",
"CreatedDate" : ISODate("2015-07-29T06:15:20.520+0300"),
"ServiceList" : [
1,5,8
]
}
]
}
My aim to run this code is converting Usage type from int32 to int64.It works fine.When I run the code below. something weird occours, and the type of the items inside AppList.ServiceList is converted to double from int32 itself.
db.CustomerInfo.find({}).forEach( function (item) {
if(item.AppList != undefined){
item.AppList.forEach(function (x){
x.Usage = NumberLong(x.Usage);
});
db.CustomerInfo.save(item);
}
});
and it seems like this,
{
"_id" : ObjectId("56565"),
"Contact" : "",
"Email" : "",
"AppList" : [
{
"Code" : "",
"Usage" : NumberLong(542),
"LicenceType" : "Monthly",
"CreatedDate" : ISODate("2015-07-29T06:15:20.520+0300"),
"ServiceList" : [
1.0,5.0,8.0
]
}
]
}
How can I solve this problem ?
MongoDB version:3.4.9
MongoShell version:v3.4.9

Import data from .js file with json object to mysql database

I have a javascript file which includes the data in the following format.
index = {
"me" : {
"id" : "524bd089-2a7b-4a71-ba23-16354d6351ae",
"firstName" : "A=",
"lastName" : "T",
"pictureName" : "66s2c.jpg",
"username" : "a-t"
},
"spaces" : [ {
"org" : {
"id" : "524bd089-2a7b-4a71-ba23-16354d6351ae",
"firstName" : "An",
"lastName" : "Tuli",
"pictureName" : "66s2c.jpg",
"username" : "arli"
}
}, {
"user" : {
"id" : "60c4a171-172f-4f66-9014-8b4cf3e476e6",
"firstName" : "Ban",
"lastName" : "Idris",
"pictureName" : "../../../../default-pic/butterfly_200.png",
"username" : "banun-idris"
}
} ]
}
users["524bd089-2a7b-4a71-ba23-16354d6351ae"] = {
"id" : "524bd089-2a7b-4a71-ba23-16354d6351ae",
"firstName" : "A",
"lastName" : "T",
"pictureName" : "66s2c.jpg",
"username" : "a",
"libraries" : [ "lEy27AZavfSR", "l0yApAoo2l4b", "lJl22YOtacxY", "l0UhMCvrMmka", "lJMWpIoFnaK4", "lCZ9cYYjVJcv", "l8kynpyoaej7" ]
}
libraries["lEy27AZavfSR"] = {
"id" : "lEy27AZavfSR",
"name" : "My Main Library",
"description" : null,
"numKeeps" : 0,
"keeps" : [ ]
}
keeps["k4r5UIugqgfk"] = {
"id" : "k4r5UIugqgfk",
"keptAt" : 1449613295000,
"lastActivityAt" : 1449613295000,
"title" : "",
"url" : "",
"note" : null,
"tags" : [ ],
"libraries" : [ "lJl22YOtacxY" ],
"summary" : "",
"messages" : [ ]
}
I need to import data from this type of format into my mysql database.
I can't finalize and nail down the approach to do this
I tried to get the file content into a php file and then convert them into a array string but i get a null result.
$jsondata = file_get_contents('trial_data.js');
$data = json_decode($jsondata, true);
var_dump($data);
The second approach I think i can take is load the data in jquery file and send it using AJAX to a php file which adds it to the database.
Which approach do you think i should take and how to go about it.
Plus i need to figure out the ID from the first index array, so that I can get the ID from the me and org object for which i need to get the rest of the information
Since your data is not a valid JSON, you can use a regex to parse it, like this:
$file_content = file_get_contents('trial_data.js');
preg_match_all("/(\w+)\[\"([^\]]*)\"\]\s*\=\s*\{([^\}]*)\}/", $file_content, $matches);
foreach ($matches[1] as $key => $value) {
$data[$value][$matches[2][$key]] = json_decode('{'.$matches[3][$key].'}');
}
print_r($data);
//For example:
echo $data['users']['524bd089-2a7b-4a71-ba23-16354d6351ae']->pictureName;
//Output: 66s2c.jpg
Demo: https://3v4l.org/fW5gH

How to delete deep array in mongodb?

I am trying to delete "virtualNumber" : "12345" in the following document:
{
"_id" : ObjectId("50a9db5bdc7a04df06000005"),
"billingInfo" : null,
"date" : "dsfdsfsdfsd",
"description" : "sdfsdff",
"pbx" : {
"_id" : ObjectId("50a9db5bdc7a04df06000006"),
"did" : {
"1234567890" : {
"inventoryId" : "509df7547e84b25e18000001",
"didcountry" : "india",
"didState" : "bangalore",
"routeType" : "CallForward",
"didNumber" : "1234567890",
"didVirtualNumbers" : [
{
"virtualNumber" : "12345"
},
{
"virtualNumber" : "56789"
}
],
"id" : ObjectId("50a9db9acdfb4f9217000002")
}
},
},
I am using node.js, so I constructed a query in JavaScript:
var query = {_id: ObjectId("50a9db5bdc7a04df06000005")};
var obj = {};
obj["pbx.did.1234567890.didVirtualNumbers.virtualNumber"]=12345;
//problem
collection.update(query,{$pull:obj});
You need to match the array element like:
{"$pull": {"pbx.did.7259591220.didVirtualNumbers": {"virtualNumber": "12345"}}}
So you should change your code to:
obj["pbx.did.7259591220.didVirtualNumbers"]={"virtualNumber": "12345"};
Please refer to http://www.mongodb.org/display/DOCS/Updating#Updating-%24pull
It mentions the pull field should be an array.

Categories