Query to fetch details from Cosmos DB - azure

I need to fetch the list of persons from an array(Ex: String[] getPersons) as input. I can't figure out how to compare and fetch data from Cosmos DB using a LINQ expression. I experimented with GetItemLinqQueryable, but I don't know if it's the right way to use it.
var db = Client.GetDatabase(databaseId);
var container = db.GetContainer(containerId);
var q = container.GetItemLinqQueryable<Person>();
var iterator = q.Where(p => p.Name == getPersons[0]).ToFeedIterator();
var results = await iterator.ReadNextAsync();
If I am using the above one, I could only able to get only the first person result but I need to get the other persons in the array as well.

You can use Contains. It is equivalent to ARRAY_CONTAINS in Cosmos DB Array functions.
You can try this code:
var iterator = q.Where(p => getPersons.Contains(p.Name)).ToFeedIterator();

Related

How to bind array to IN condition with Node postgres

I'm struggling to figure out of to bind an array to an IN query in node pg library.
const env = 'foo';
const sourceTypes = ['one', 'two'];
const resp = await pool.query(
`SELECT source_id, target_id FROM records
WHERE target_env = $1
AND source_type IN ($2)`,
[env, sourceTypes],
);
I've tried several variations and they either error out or don't return any data.
I can make the query when I just use when I manually bind to generate something like this:
SELECT source_id, target_id FROM records
WHERE target_env = 'foo'
AND source_type IN ('one', 'two')
PS: If can provide suggestion on how to actually see the SQL request that PG is generating, that would be extremely helpful!
You can't bind an array to multiple elements of a list in one go. But you can use an array instead of a list by changing in ($2) to =ANY($2)
You can see what queries are getting sent by setting log_statement=all and then viewing the PostgreSQL log file.

Firebase compound queries always get empty results

I'm trying to create a query in my nodesjs server (functions section) in firebase
I created a collection with 3 documents and 2 fields each - email and timestamp
when I do a query for email -> I get the right documents
await admin.firestore().collection('sessions').where('email', '==', 'email#gmail.com').get()
when I do a query for timestamp -> I get the right documents
await admin.firestore().collection('sessions').where('timestamp', '>', 1601164800).get()
but...
when I do a query for both email and timestamp -> I get no documents...
await admin.firestore().collection('sessions').where('email', '==', email).where('timestamp', '>', 1601164800).get()
the way I understand it is when I do multiple 'where' it's like a logical AND so if I get the same records in the first query and the seconds query I should get them in the third query as well
I also read that I need to create an index in case I want to do multiple where that have an equal operator and range operator so I created one and no luck :(
all the data I created manually - both the collection + documents and the index
is there something that I miss?
collection data
indexes definition
this is the code of full process of getting the docs
the result array I return to the client and I get an empty array
async function getInfo() {
let query = admin.firestore().collection('sessions').where('email', '==', 'email#gmail.com').where('timestamp', '>', 1601164800);
let dbData = await query.get();
let result = [];
dbData.forEach(doc => {
let data = doc.data();
// this log is to see how many docs I get
logger.log(data);
result.push(data);
});
return result;
}
What about iterating over dbData.docs?
logger.log(`Documents retrieved: ${dbData.size}`)
return dbData.docs.map(doc => doc.data())
https://googleapis.dev/nodejs/firestore/latest/QuerySnapshot.html

Sails.js: How to find records based on values in associated collection?

I'm looking for a way to make sub-query using Sails.js Waterline. The record has an association with Charge model.
I would expect something like that to work, but that doesn't seem to be supported:
var topRecords = await Record.find({'charge.paid':true});
The closest I got was this:
var topRecords = await Record.find().populate('charge',{paid:true});
but the problem is that it still returns all the Records regardless, just doesn't populate the records that do not match populate where statement.
The reason why I can't search for charges first is that I want to sort the data based on one of the values in Record.
You can fetch the Charges then use .map to get the records from there.
const topCharges = await Charge.find({ paid: true }).populate('records');
const topRecords = topCharges.map(charge => charge.record);

How to get all keys + in a collection + mongodb +mongoose

I want to get all distinct keys from a collections in mongoDB.
I refereed the following links:
Get names of all keys in the collection
Querying for a list of all distinct fields in MongoDB collection and etc.
But still i didn't get the right solution...
As i am using mongoose in the first link reference syas runCommand is not a function.
As findOne() will give the first document keys alone but i need all distnct keys
userModel.findOne(condition, projection, callback)
Please share your ideas..
If you are using Mongoose 3.x, then you can try this :
userModel.find().distinct('_id', function(error, ids) {
// ids is an array of all ObjectIds
});
Or you can find all the documents and extract key from that like :
var keys = {};
var docKeys = [];
userModel.find({}, function(err, allDocs){
allDocs.forEach(function(doc){
docKeys = Object.keys(doc);
docKeys.forEach(function(docKey){
if(!keys[docKey]) keys[docKey] = true;
})
})
})
I have just written for getting logic, you can change according to your requirements and efficiency
Try like this you will get all of your keys defined into your mongoose model/Schema.
import Model from 'your_model_path'
for(let property in Model.schema.obj){
console.log("key=====>",property);
}

Forming mongo query from String

I am using mongo-parse to parse the mongo queries. Below is my code
var parser = require('mongo-parse')
var queryObject = parser.parse({"city":"Paris"})
//Getting field and value separately
//Field = city
//Value = Paris
var string = 'db.employee.find({"city":"Paris"},{"emp_id":1}'
//Not able to get the field and value separately from string
Is there any node module to generate the mongo query from the above string.
Any help on this will be really helpful
it doesn't look like mongo-parse returns any information about the collection. considering this, couldn't you just take the analysis you get from the parser and hand-construct the query from the data (assuming i'm understanding your question correctly)
e.g.
var newQuery = {};
newQuery[queryObject.field] = queryObject.value;
db.employee.find(newQuery, {emp_id: 1});

Resources