I don't know how should refer I to a table, maybe someone knows and can help:
Collection:
{
"_id" : ObjectId("5a5e40636494620e7471c51b"),
"uczelnia" : "Politechnika Wroclawska",
"ulica" : "Jodlowa 15",
"doktorzy" : [
{
"imie" : "Mateusz",
"nazwisko" : "Laskowski"
},
{
"imie" : "Piotr",
"nazwisko" : "Potrzebny"
}
],
"miejscowosc" : "Wroclaw"
}ObjectId("5a5e40636494620e7471c51b"
Function:
function dane_o_uczelni(id) {
uczelnia1= db.uczelnia.findOne({"_id" : id})
if(uczelnia1!==null)
{
print("Uczelnia: "+ uczelnia1.uczelnia)
print("Miejscowosc: " + uczelnia1.miejscowosc)
print("Doktorzy: " + uczelnia1.doktorzy.nazwisko)
}
else return null
}
dane_o_uczelni(ObjectId("5a5e40636494620e7471c51b"));
I want to see on output all of my Doctor(doktorzy) in ObjectId("5a5e40636494620e7471c51b" with surname (nazwisko). With this code I see only uczelnia and ulica, in nazwisko I see information undefined..
Related
I am calling google Places API which returns a JSON response similar to this, from this responss I would like to extract all the name objects and store them in an array:
{
"html_attributions" : [],
"next_page_token" : "CpQCAgEAAFxg8o-eU7_uKn7Yqjana-",
"results" : [
{
"geometry" : {
"location" : {
"lat" : -33.867217,
"lng" : 151.195939
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/cafe-71.png",
"id" : "7eaf747a3f6dc078868cd65efc8d3bc62fff77d7",
"name" : "Biaggio Cafe - Pyrmont",
"opening_hours" : {
"open_now" : true
},
"photos" : [
{
"height" : 600,
"html_attributions" : [],
"photo_reference" : "CnRnAAAAmWmj0BqA0Jorm1_vjAvx1n6c7ZNBxyY-U9x99-oNyIBE",
"width" : 900
}
],
"place_id" : "ChIJIfBAsjeuEmsRdgu9Pl1Ps48",
"price_level" : 1,
"types" : [ "cafe", "bar", "restaurant", "food", "establishment" ],
"vicinity" : "48 Pirrama Rd, Pyrmont"
},
{
"geometry" : {
"location" : {
"lat" : -33.866786,
"lng" : 151.195633
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "3ef986cd56bb3408bc1cf394f3dad9657c1d30f6",
"name" : "Doltone House",
"photos" : [
{
"height" : 1260,
"html_attributions" : [ "From a Google User" ],
"photo_reference" : "CnRwAAAAeM-ag",
"width" : 1890
}
],
"place_id" : "ChIJ5xQ7szeuEmsRs6Kj7YFZE9k",
"reference" : "CnRvAAAA22k1PAGyDxAgHZk6ErHh_h_mLUK_8XNFLvixPJHXRbCzg-",
"types" : [ "food", "establishment" ],
"vicinity" : "48 Pirrama Rd, Pyrmont"
},
{
"aspects" : [
{
"rating" : 23,
"type" : "overall"
}
],
...
],
"status" : "OK"
}
In my code, I would like to store all instances of name in an array. I'm not really sure how to do this, but what I'm doing right now is definitely not working, the array remains empty after console logging it.
var place_search = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=" + encodeURIComponent(agent.parameters.cuisine) + "restaurant" + "®ion=sg&location=" + lat + "," + long + "&radius=" + user_proximity + "&opennow" + "&key=" + api_key;
return axios.get(place_search)
.then(response => {
const { place_id, name, formatted_address } = response.data.results;
placeArray.push({
name: name,
place_id: place_id
});
)}
There are a number of issues with your code, and it isn't clear what you think each part is trying to do, but the biggest issue seems to be with how you're handling the call with axios inside the loop. In particular, there seem to be two issues:
You're returning the value from the call - this breaks out of the loop after executing the then portion the first time.
Related to this, the code after the return can't get executed (you've returned from the function), so you never evaluate if the rating is greater than 4.
Assuming you're trying to loop through the places in placeArray and make a network call with axios for each one, you may want to use await, which is available in more modern versions of node. It might look something like this:
for (var i = 0; i < placeArray.length; i++) {
var place_details = "https://maps.googleapis.com/maps/api/place/details/json?place_id=" + placeArray[i].place_id + "&fields=rating&key=" + api_key;
const response = await axios.get(place_details);
const ratings = response.data.result.rating;
if (ratings > 4 ){
agent.add(`Ok I recommend ` + JSON.stringify(placeArray[i].name) + ` and the address is ` + JSON.stringify(placeArray[i].formatted_address));
agent.add(`It is rated ` + placeArray[i].ratings )
break;
}
}
I have one collection with this document format:
{
"_id" : ObjectId("5c51fe3a6abdf0e5cd78f658"),
"0" : {
"id" : 1,
"name" : "carlos"
},
"1" : {
"id" : 2,
"name" : "foo"
},
"2" : {
"id" : 3,
"name" : "Jhon Doe"
},
"3" : {
"id" : 4,
"name" : "Max"
}
}
the only way to access the properties was doing a foreach loop and another for in inside.
db.getCollection('tutorial').find({}).forEach( (users) => {
for(user in users){
print("ID-> " + users[user].id, " Name->" + users[user].name);
}
});
But I can only print the results, there is another way to return a value using find ?
Thanks in advance.
You have to split up your operations. Get the collection first and then run a function to return the value you wish:
let collection = db.getCollection('tutorial').find({});
let name = () => {collection.forEach( (users) => {
for(user in users){
if(users[user].name == "foo"){
return ("ID-> " + users[user].id, " Name->" + users[user].name);
}
}
})};
or simply create a variable and set it when you run the loops
let name;
db.getCollection('tutorial').find({}).forEach( (users) => {
for(user in users){
name = ("ID-> " + users[user].id, " Name->" + users[user].name);
}
});
or something similar
Though all of these scenarios seem like a strange way to handle a mongo collection. I would definitely recommend restructuring your collection if you can't access the data using regular find method.
I'm trying to print the values of an nested array.But getting execute script error.How do I print object BSON and avoid error in for nested array.
Note : I want to do with print and not find().
Customer schema
{
"name" : "Sam",
"phone" : [
{
"home" : "123456",
"work" : "045842"
}]}
query
db.getCollection('customer').find({}).forEach( function(cust)
{
print("Customer Name : " + cust.name); // prints Sam
print("Home Contact : " + cust.phone) // prints [object BSON]
print("Home Contact : " + cust.phone.home) // throws error
});
You could use aggregation if there are multiple items in the array
db.collectionName.aggregate([
{ $unwind: { path: "$phone", preserveNullAndEmptyArrays: true}},
]).forEach(function(doc){
print(doc.name)
if(doc.phone !== undefined) print(doc.phone.home)
if(doc.phone !== undefined) print(doc.phone.work)
})
You just need to convert the object to string and access the array;
print("Home Contact : " + JSON.stringify(cust.phone[0]))
// prints ` Home Contact: { "home" : "123456", "work" : "045842" }
print("Home Contact : " + cust.phone[0].home) // "123456"
An example:
aireclaimRs:PRIMARY> use test
switched to db test
aireclaimRs:PRIMARY> db.createCollection('customer')
{ "ok" : 1 }
aireclaimRs:PRIMARY> db.customer.insert( {
... "name" : "Sam",
... "phone" : [
... {
... "home" : "123456",
... "work" : "045842"
... }]})
WriteResult({ "nInserted" : 1 })
aireclaimRs:PRIMARY> db.getCollection('customer').find().forEach(function(cust){
... print("Customer Name : " + cust.name);
... print("Homes Contact : " + JSON.stringify(cust.phone[0]));
... print("Home Contact : " + cust.phone[0].home)
... })
Customer Name : Sam
Homes Contact : {"home":"123456","work":"045842"}
Home Contact : 123456
Here is an example of my MongoDb structure :
{
"id" : 1,
"children" : [
{
"id" : 2,
"status" : " fsdfsdf "
},
{
"id" : 3,
"status" : " ffdfg "
},
{
"id" : 4,
"status" : " fsdfsdfsdfdsf "
}
]
}
I wanted to trim records in mongodb, so i did :
db.getCollection('myCollectionName').find().forEach(function (doc){
for (subDoc of doc.children) {
if(typeof subDoc.status === 'string') {
subDoc.theText = subDoc.theText.trim();
}
}
db.getCollection('myCollectionName').save(doc);
})
But i got this error :
E QUERY SyntaxError: Unexpected identifier
You use wrong identifier — the array item doesn't have theText identifier.
var docs = db.getCollection('myCollectionName').find()
docs.forEach(function (doc) {
for (subDoc of doc.children) {
if(typeof subDoc.status === 'string') {
subDoc.status = subDoc.status.trim();
}
}
db.getCollection('myCollectionName').save(doc);
})
Step by Step instructions
Open local mongo shell with db stackoverflow
⋊> ~ mongo stackoverflow
MongoDB shell version v3.4.1
connecting to: mongodb://127.0.0.1:27017/stackoverflow
MongoDB server version: 3.4.0
Insert one (your) document
> db.getCollection('myCollectionName').insertOne({
... "id" : 1,
... "children" : [
... {
... "id" : 2,
... "status" : " fsdfsdf "
... },
... {
... "id" : 3,
... "status" : " ffdfg "
... },
... {
... "id" : 4,
... "status" : " fsdfsdfsdfdsf "
... }
... ]
... })
{
"acknowledged" : true,
"insertedId" : ObjectId("588b4984522a4f31ff6bc738")
}
Find inserted document
> db.getCollection('myCollectionName').findOne()
{
"_id" : ObjectId("588b4984522a4f31ff6bc738"),
"id" : 1,
"children" : [
{
"id" : 2,
"status" : " fsdfsdf "
},
{
"id" : 3,
"status" : " ffdfg "
},
{
"id" : 4,
"status" : " fsdfsdfsdfdsf "
}
]
}
I use findOne because I know in db only one document. In normal situation you need use find and pretty to find all document in collection
> db.getCollection('myCollectionName').find().pretty()
Find documents in collection and save cursor in variable
> var docs = db.getCollection('myCollectionName').find()
Run function for trim only field status in array children in documents
> docs.forEach(function (doc) {
... for (subDoc of doc.children) {
... if(typeof subDoc.status === 'string') {
... subDoc.status = subDoc.status.trim();
... }
... }
...
... db.getCollection('myCollectionName').save(doc);
... })
Improvement for production: find only documents with field children and check fields into document exists.
Check the result (find the document)
> db.getCollection('myCollectionName').findOne()
{
"_id" : ObjectId("588b4984522a4f31ff6bc738"),
"id" : 1,
"children" : [
{
"id" : 2,
"status" : "fsdfsdf"
},
{
"id" : 3,
"status" : "ffdfg"
},
{
"id" : 4,
"status" : "fsdfsdfsdfdsf"
}
]
}
I have the next document in a collection:
{
"_id" : ObjectId("546a7a0f44aee82db8469f6d"),
...
"valoresVariablesIterativas" : [
{
"asignaturaVO" : {
"_id" : ObjectId("546a389c44aee54fc83112e9")
},
"valoresEstaticos" : {
"IT_VAR3" : "",
"IT_VAR1" : "",
"IT_VAR2" : "asdasd"
},
"valoresPreestablecidos" : {
"IT_ASIGNATURA" : "Matemáticas",
"IT_NOTA_DEFINITIVA_ASIGNATURA" : ""
}
},
{
"asignaturaVO" : {
"_id" : ObjectId("546a3d8d44aee54fc83112fa")
},
"valoresEstaticos" : {
"IT_VAR3" : "",
"IT_VAR1" : "",
"IT_VAR2" : ""
},
"valoresPreestablecidos" : {
"IT_ASIGNATURA" : "Español",
"IT_NOTA_DEFINITIVA_ASIGNATURA" : ""
}
}
]
...
}
I want modify an element of the valoresEstaticos, I know the fields "_id", "asignaturaVO", and the key of the item valoresEstaticos that I want modify.
Which is the correct query for this?, I have this:
db.myCollection.findAndModify({
query:{"_id" : ObjectId("546a7a0f44aee82db8469f6d")},
update: {
{valoresVariablesIterativas.asignaturaVO._id: ObjectId("546a389c44aee54fc83112e9")},
{ $set: {}}
}
})
but I dont know how to build a query :(
Help me please, Thank you very much!
You can just use update.
db.myCollection.update(
{ "_id" : ObjectId("546a7a0f44aee82db8469f6d"), "valoresVariablesIterativas.asignaturaVO._id" : ObjectId("546a389c44aee54fc83112e9") },
{ "$set" : { "valoresVariablesIterativas.$.valoresEstaticos.IT_VAR3" : 99 } }
)
assuming you want to update key IT_VAR3. The key is the positional update operator $. The condition on the array in the query portion of the update is redundant for finding the document, but necessary to use the $ to update the correct array element.