How to find a document using nested value MongoDB - node.js

I have a Json like this:
"datos_personales":
{
"nombre":"Dionel",
"apellido":"Delgado",
"fechanacimiento":"1990-12-31T04:00:00.000Z",
"lugarNacimiento":"Venezuela, Maracaibo",
"edad":25,
"genero":"Masculino",
"cedula":"21076754",
"direccion":"San Carlos",
"telefonofijo":"0262-6871111",
"telefonomovil":"0262-6871111"
},
"datos_emergencia":
{
"nombre1":"Jeaynie",
"apellido1":"Valbuena",
"telefono1":"0262-6871111",
"telefono2":"0262-6871111",
"parentesco1":"Madre",
"nombre2":"Diones",
"apellido2":"Delgado",
"telefono3":"0262-6871111",
"telefono4":"0262-6871111",
"parentesco2":"Padre"
},
"datos_sociales":
{
"civil":"Soltero",
"estudios4":true,
"ocupacion":"Programador Web",
"hijos":"No"
},
"datos_medicotratante":
{
"nombre":"Naikelin",
"apellido":"Ruiz",
"telefono1":"0262-6871111",
"telefono2":"0262-6871111",
"especialidad":"PediatrĂ­a",
"sangre":"AB",
"rh":"Negativo",
"seguro":"No"
}
`
I need to query these kinds of documents with nodeJS using "cedula" to find them
{"datos_personales.cedula":21076754} << in this case
I tried using this but it doesn't fetch the document
var ced = 21076754;
db.getCollection('users').find({"datos_personales.cedula":ced});
any suggestions?

"cedula":"21076754",
Your result is a string (See the quotes).
Change your query to:
var ced = "21076754";
db.getCollection('users').find({"datos_personales.cedula":ced});

Another solution to the problem is -
find() query in MongoDB returns a cursor while findOne() query returns a JSON Object which matches the argument passed in the query. You can retrieve the desired record by using the query below -:
db.getCollection('users').findOne({"datos_personales.cedula":ced});

Related

Can't get $or statement to work in nodejs and mongodb

In nodejs I'm trying to run an $or statement to retrieve objects from mongo that could have certain IDs. I use a for loop to push the ids into a string. My code looks like this after the loop.
var filter = "{ $or: [{'id':1290383},{'id':1290381},{'id':1290382}]}"
const results = await collection.find(filter).toArray();
When I run this it returns everything in the collection. I'm assuming I need to JSON parse it beforehand but I get an error about the $ when I try to parse it. I can't find any information about the correct way to use $or in nodejs. I feel like there should be another way to query different IDs. If someone knows, please let me know.
You need to convert the filter variable from string to json object as follow:
var filter = '{ "$or": [{"id":1290383},{"id":1290381},{"id":1290382}]}'
var filterobj = JSON.parse(filter);
const results = await collection.find(filterobj).toArray();
Also JSON.parse() does not allow single quotes so you will need to enquote the full string with single quotes and the keys with the double quotes.
You could also replace the $or operation with $in operation for the same task (since it is generally easier to read and pretend to be more effective) as follow:
var filter = '{ "id":{"$in": [1290383,1290381,1290382] } }'
example from mongo shell:
mongos> var filter = '{ "id":{"$in": [1290383,1290381,1290382] } }'
mongos> var filterobj = JSON.parse(filter);
mongos> filterobj
{ "id" : { "$in" : [ 1290383, 1290381, 1290382 ] } }
mongos>

cosmosdb geospatial look up return blank

I am using cosmosDB to do a $geowithin lookup and when i run the query in the cosmosdb data explorer it works fine and returns the right set. When i run it in node js using the MongoClient I get back a empty set.
This is the query i ran in cosmosdb data explorer:
{CurrentLoc: {
$geoWithin: {
$centerSphere: [[-122.0312186,37.33233141], 0.0025232135647961246]
}
}}
That returned the correct list of documents
This is in my node app:
var toFind = {
CurrentLoc: {
$geoWithin: {
$centerSphere: [currentLoc, maxDistance]
}
}
}
var query = db.collection('User').find(toFind)
query.toArray(function (err, doc, queryResult) {
logger.debug ('result: ' + JSON.stringify(doc);
})
That returns a blank set and does not get the data back. Why would it be returning different things and also why is it blank?
You might need to break down the currentLoc variable into an array of two values, so the query is structured in the same manner as when executed through CosmosDB Data Explorer:
[-122.0312186,37.33233141] in
$centerSphere: [[-122.0312186,37.33233141], 0.0025232135647961246]
Hope it helps!

Convert a string parameter into float in Cloudant query

I need to do a query in an Cloudant DataBase where you compare a number with decimals that is defined as a string with another number sent from the server. The problem is that a comparison of strings is made and I need it to be a numerical comparison. There is there any way to perform this search by converting the database parameter to float while doing the query? O there are another way to do this query?
This is the query in the server, value.precio is sent from the client as a string.
value.precio = value.precio.split("-");
var precio_init = value.precio[0];
var precio_final = value.precio[1];
value.precio = {
"$gte":precio_init,
"$lte":precio_final
};
And in my database this is the parameter I want to search is:
"precio": "13.39"
Thanks
I don't think you will be able to do this with Cloudant Query, but you could try Cloudant Search. Create a new search index similar to the following:
Design Doc: myDesignDoc
Index Name: byPrecio
Index:
function (doc) {
if (doc.precio) {
index("precio", parseFloat(doc.precio));
}
}
Then you can uses ranges to search. For example:
precio:[13 TO 14]
Full search on Cloudant would look like this:
https://xxx.cloudant.com/YOUR_DB/_design/myDesignDoc/_search/byPrecio?q=precio:[13%20TO%2014]&include_docs=true
Sample response:
{
"total_rows":1,
"bookmark":"g2wAAAAxxx",
"rows":[
{
"id":"74fa6ff1b6dbca8c10d677832f6a3de2",
"order":[
1.0,
0
],
"fields":{
},
"doc":{
"_id":"74fa6ff1b6dbca8c10d677832f6a3de2",
"_rev":"2-17c984e51102b719fe9f80fc5d5bc78e",
"precio":"13.39",
"otherField":"otherValue"
}
}
]
}
More info on Cloudant Search here

Arangodb javascript cursors db._query()

I'm using arangodb cursor through javascript client
db._query('query', {param: value})
My query contains limit operator and I need a total count. How can I pass fullCount option into cursor and read extra.fullCount back.
If you're running the query from the ArangoShell, then the easiest should be setting the options attribute when calling db._query() like this:
var data = {
query: "FOR doc IN collection FILTER doc.attr == #value LIMIT 0, 5 RETURN doc",
bindVars: { value: "foo" },
options: { fullCount: true }
};
var result = db._query(data);
full = result.getExtra().stats.fullCount;
The options object is optional. If it contains a fullCount subattribute, the query result will contain a fullCount subattribute in its statistics. In the above example, the result is captured in variable full.

ElasticSearch: how to mix terms query with wildcard

Say, I have the following query: 'document spreadsheet app*'. I want to construct the query dictionary which is equivalent to this type of query '_search?q=_all:document+spreadsheet+app*'. Say, query_words_list = ['document', 'spreadsheet', 'app']. I tried this:
{
'query': {
'terms': {
'_all': query_words_list[:-1] + [query_words_list[-1] + '*'],
}
}
}
However, if you compare results of two queries, they are not equivalent. Any hints what query dictionary equivalent to '_search?q=_all:document+spreadsheet+app*' can look like? Thanks in advance!
The q parameter is equivalent to Query String Query.

Resources