MongoDB converting from int32 to double itself - javascript

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

Related

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

Firebase query taking forever

My firebase data looks like this...
In JSON down below...
I've been trying to use what I've found in their docs to query the db so that I end up with of all the terms and their keys. How do I query just the term property and key for every node under vocab? I'm using this to populate an autosuggest. Also, the 0 and 1 under the vocab node are keys... they showed up that way when I imported the data as a JSON file. Any new vocab goes in with unique long key values though.
I've tried both .on() and .equalTo()... But I have had no luck whatsoever. It always seems to be grabbing everything in the entire vocab node of the database and taking on the order of 7 whole seconds to do it each time. Here is an example of one of my attempts where I try to put just the terms into an array...
let termList = [];
const termsRef = firebase.database().ref('vocab/');
termsRef.on('child_added', snap => termList.push(snap.val().term));
This doesn't even get the keys (which I need) and it still takes around 7 seconds to do it. I've seen videos where people do things like this in one line and it goes quick... not my luck. Any help would be much appreciated.
As requested here is a JSON sample of one of the database nodes... there are over 400 like this... the relevant property is term... all the way at the bottom. I need an array of terms and firebase database keys. How do I get them with a query?
{
"date" : "2016-07-26T14:50:10.906Z",
"defs" : [ {
"AddedBy" : "",
"date" : "2016-07-26T14:50:10.906Z",
"def" : "it's your need to fulfill or to obtain your full potential, and have meaningful goals.",
"image" : ""
}, {
"AddedBy" : "",
"date" : "2016-07-26T14:50:10.906Z",
"def" : "the very last stage in priority in order to be happy.",
"image" : ""
}, {
"AddedBy" : "",
"date" : "2016-07-26T14:50:10.906Z",
"def" : "the need to be able to set goals and reach them and be able to accept one's self.",
"image" : ""
} ],
"examples" : [ {
"AddedBy" : "",
"addDate" : "2016-07-26T14:50:10.906Z",
"approved" : true,
"checkDate" : "2016-07-26T14:50:10.906Z",
"example" : "a self-actualizing person is a person who accepts themselves, sets realistic and meaningful goals and accepts change.",
"feedback" : {
"comment" : "",
"grammarTrouble" : false,
"incorrect" : false,
"moreSpecific" : false,
"noContext" : false
},
"nonExample" : false,
"seenRecently" : [ {
"sawOn" : "",
"user" : ""
} ]
}, {
"AddedBy" : "",
"addDate" : "2016-07-26T14:50:10.906Z",
"approved" : true,
"checkDate" : "2016-07-26T14:50:10.906Z",
"example" : "who is not self-actualizing is a person who dislikes themselves, has no goals in life, and refuses to accept change.",
"feedback" : {
"comment" : "",
"grammarTrouble" : false,
"incorrect" : false,
"moreSpecific" : false,
"noContext" : false
},
"nonExample" : false,
"seenRecently" : [ {
"sawOn" : "",
"user" : ""
} ]
}, {
"AddedBy" : "",
"addDate" : "2016-07-26T14:50:10.906Z",
"approved" : true,
"checkDate" : "2016-07-26T14:50:10.906Z",
"example" : "Someone who achieves to their best personal ability and faces every situation head on.",
"feedback" : {
"comment" : "",
"grammarTrouble" : false,
"incorrect" : false,
"moreSpecific" : false,
"noContext" : false
},
"nonExample" : false,
"seenRecently" : [ {
"sawOn" : "",
"user" : ""
} ]
} ],
"term" : "Self Actualization",
"unit" : 0
},

Getting subset of json from ElasticSearch

I want to have a subset of json response from ElasticSearch server. I am new to ElasticSearch and JavaScript. Please have a look. The json file is the example file here from ElasticSearch doc. This is a sample:
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 1000,
"max_score" : 1.0,
"hits" : [ {
"_index" : "bank",
"_type" : "account",
"_id" : "4",
"_score" : 1.0,
"_source":{"account_number":4,"balance":27658,"firstname":"Rodriquez","lastname":"Flores","age":31,"gender":"F","address":"986 Wyckoff Avenue","employer":"Tourmania","email":"rodriquezflores#tourmania.com","city":"Eastvale","state":"HI"}
}, {
"_index" : "bank",
"_type" : "account",
"_id" : "9",
"_score" : 1.0,
"_source":{"account_number":9,"balance":24776,"firstname":"Opal","lastname":"Meadows","age":39,"gender":"M","address":"963 Neptune Avenue","employer":"Cedward","email":"opalmeadows#cedward.com","city":"Olney","state":"OH"}
}
................................
]
}
}
How to extract an array of account_number, balance and lastname for example [{"account_number":9,"balance":24776,"lastname":"Meadows"},{"account_number":4,"balance":27658,"lastname":"Flores"}, ......... ].
Here is the code I used:
var deferred = $q.defer();
$http.get("http://localhost:9200/bank/_search?q=*").success(function(data){
var country=data.hits.hists.map( function (count) {
return {
account_number: count._source.account_number,
balance: count._source.balance,
lastname: count._source.lastname
};
});
deferred.resolve(country);
});
return deferred.promise;
I took inspiration from similar codes like this one for the REST call. It seems that the data I got is undefined. Is there a configuration to do from ES side?
You can instruct ES to only return those fields using source filtering:
$http.get("http://localhost:9200/bank/_search?_source=account_number,balance,lastname&q=*").success(function(data){
That way you don't have to filter out the fields by yourself.
Then you have a typo on the next line: hists should read hits
var country=data.hits.hits.map( function (count) {
Please try it out.

Unable to print BSON object from 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.

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