How to find data from array in mongodb - javascript

I have collection like this:
{
"name":"silver",
mywants:[
{"_id":objid(545454ddfdf5),mark:{"english":100,"math":100,"science":100}},
{"_id":objid(5878784dfd5d),mark:{"english":100,"math":100,"science":100}},
{"_id":objid(5454dfd44545),mark:{"english":100,"math":100,"science":100}},
{"_id":objid(541dfee88245),mark:{"english":100,"math":100,"science":100}},
]
}
I want to find that given objid is exist in mywants array or not. Then if exist that objid i want that exist object id document to my callback function so i have tried like this
collection.find("{"name":"silver"},{"mywants._id":objid}).toArray(function(err,res)
{
console.log(JSON.stringify(res));
})
But, I got output like
[{"Mywant":[{"_id":"5128b9bc046802720b000003"},
{"_id":"5128c190046802720b000004"},
{"_id":"5128c359175e1aa80b000001"}],"_id":"5128b71455e4e0540b000002"}
]
But i want like this
{"_id":objid(545454ddfdf5),mark:{"english":100,"math":100,"science":100}}`,
How to find?

You have to call
collection.find({"name":"silver", "mywants._id":objid}).toArray(…)
instead of
collection.find({"name":"silver"},{"mywants._id":objid}).toArray(…)
. The former one represents a query with two expressions ("name":"silver" AND "mywants._id":objid) while the latter one is one expression ("name":"silver") and one projection ("mywants._id":objid) [controls the fields to return]. More info at http://docs.mongodb.org/manual/reference/method/db.collection.find/.

You have typo in your code, it is not ver clear what youwant. Based on your sample with typo and output you want (again with typo) I assume this is what you meant:
-You are doing a find on name:"silver" and want back mywants._id field (has typo) with that syntax.
Instead I assume you meant to find:
name:"silver" AND "mywants._id" : someSpecificId
and output corresponding mywants entry:
db.collection.find({"name":"silver","mywants._id":objid}, {"mywants.$":1, _id:0}).pretty()

Related

How do I parse part of a JSON object that has mixed string and numbers?

I have a JSON file that was processor generated with lines like this
jsonData: "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}"
I can target the 'jsonData' object but that returns everything within the double quotes as a string.
I tried ...dataset[0].jsonData[8] which returns the '3' from the first value. I guess I could throw the mixed strings into a JS function and use regex to remove the extra stuff, but thats probably the hackyest way to do this.
Whats the easiest way to target the values only?
If you want to interact with it like the list I would consider something like
var list = jsonData.split("[")[1].split("]")[0].split(",")
Console.log(list);
The console reads:
[
'350.23', '250.32',
'150.34', '340.50',
'236.70', '370.45',
'380.55'
]
From here you can use list[3] to get 340.50
If you don't want to spend the time fixing your JSON just do this:
let values = "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}".split(',').map(_ => _.replace(/[^0-9.]/g,''))
console.log(values)

How to update an array of objects?

For example,
{
id:"monday",
names:[
{one:"white", two:"pink"},
{uno:"blanco", dos:"rosado"}
]
}
How would you change white to black?
So far, I've got this:
r.db.table.get('monday').update({
names: r.row("names").nth(0)
})
Which specifies the 0th index of names, but not sure how to further specify the one field and then change it.
What you have so far is pretty correct but you replace names with its first sub-object (I guess you saw that result already).
You just need to use a merge to alter the sub-object, and a changeAt on names to put the altered sub-object in the array, just like this:
r.db.table.get('monday').update({
names: r.row('names').changeAt(0, r.row('names').nth(0).merge({one: 'black'}))
})
Hope this helps!
Maybe your data is stored in an object with the name of obj; something like
var obj = {...}
you can make this work:
obj.names[0].one = "black";
I have actually tried it using firebug no issues.
Each element in the array is independent so no worries.
First off all, you should use replace instead of update.
Get record without names field.
merge it with new names (remove 1st element from it, add at the 1st position new element in which we replaced white to black in one field)
Something like this:
r.db.table.get('monday').replace(function(doc){
return doc.without({names: true}). merge({
names: doc("names").deleteAt(0).prepend(doc("names").nth(0).merge({
one : "black"
}))
})
})

extracting a list of 2 property values

I have an object array:
user :[
{
name: String,
username: String
}
]
I want to view every change either to name or username.
I found underscore _.pluck only does the trick for one property (_.pluck(user, 'name')
Is there another way to have the list of both values?
With pluck you can only use one property, it simply isn't made to retrieve multiple. The method you would want to use is map, as suggested in this relevant question + answer: How to pluck multiple attributes from a Backbone collection?
Assuming you want the following output [['nameA','usernameA'],['nameB','usernameB'],...]], you could use map in the following manner:
var myResult = users.map(function(user) {
return [user.name, user.username];
});
NOTE: I changed the variable user to users to make more sense with your data.

Safe way to check if array element exists?

I have a 2D array.
I currently access that array using notation such as:
myArray[5][9] (for example).
What is the safest way to check whether or not a certain array element exists?
For example, let's say I am looping through the array and retrieving a property of each array element like so:
myArray[5][9].firstName
I then come to myArray[9][11].firstName (for example) which doesn't exist. Clearly this will throw an exception as the element doesn't exist.
How can I deal with this? I'm not looping through the entire array (i'm accessing it's contents randomly and say using myArray.lengthin a for loop will not work.
Is there a JS function / method for checking whether or not an array element exists?
Thanks.
Safe call operator ?. looks fine. Warning: many, but not all implementations (and versions) of JavaScript supports it.
For your example it will looks like
myArray[5][9]?.firstName
EDIT: Thanks to Asaf's comment there is safer version
myArray?.[5]?.[9]?.firstName
like
if (!('firstname' in myArray[i][j])) { ... }
Just check it with if condition.
if(myArray[i][j].firstName){
}
You can use the hasOwnProperty method to check if an array item exists:
if (myArray.hasOwnProperty(x) && myArray[x].hasOwnProperty(y)) {
var name = myArray[x][y].firstName;
}
This checks both dimensions. If you know that the first index (x in the example) is always inside the range, you can skip the first test.
If you store some other values in the array also, you would need to check if the item has the firstName property:
if (myArray.hasOwnProperty(x) && myArray[x].hasOwnProperty(y) && myArray[x][y].hasOwnProperty('firstName')) {
var name = myArray[x][y].firstName;
}

Getting access to array inside an object property

I have an object that I need to iterate through and it is built like this:
points[m] = {
coordinate1: 34,
coordinate2: 23,
code: ["LEM"],
location: '123 fake street'
}
If the current point(point[m]) matches another point I want to add the points[m].code to the point that it matched to build a unique array of objects like this:
pointsUnique[l].code.push(point[m].code[0]);
This works fine, except that when I try and iterate through (pointsUnique[l].code) like this:
for(var n=0;n<pointsUnique[l].code.length;n++){
var codeList = pointsUnique[l].code[n];
console.log(codeList);
}
I only get the 1 result in the code array because (pointsUnique[l].code.length) is apparently 1. Although it has 15 items in it when I view it in the console.
Any assistance on how I could access to all of the values of (pointsUnique[l].code) would be greatly appreciated.
Your logic looks good to me, so something else is probably going on. Are you copy/pasting your real code? For one, you've got a typo here:
pointsUnique[l].code.push(point[m].code[0]);
It should be points[m] not point[m].
Also, what is this mysterious l variable? It could be a problem with that, too, though there's no way of knowing from the code you've posted.

Categories

Resources