How to make a query in MongoDB using a JSON? - json

is there anyway to make a query in MongoDB using a JSON and returning a object if one field of the json matches with some in the database?
for example, I have the this object called keysArray
{ house: 'true', garden: 'false' }
and I would like to make a query in Mongo passing this object as a query field and return if some object in my database matches with at least one of those fields :
keysArray.forEach(function(key){
collection.find({keysArray}, function(err, propertyMatch){
console.log(propertyMatch)
})
})
I got no objects back, even if I have one object in my database that matches these fields.
Thanks in advance

...and I would like to make a query in Mongo passing this object as a
query field and return if some object in my database matches with at
least one of those fields.
It sounds like OR logic - if I understood it well.
On this specific case it's not possible to pass in JSON-like object to query as it would be a implicit AND logic condition.
So you should build first a OR expression and use it in collection.find(), something like this:
var myjson = {'status': 32, 'profile': {$exists: false}};
function build_logic_or(json) {
var orExpr = [];
for (var field in json) {
var expr = {};
expr[field] = json[field];
orExpr.push(expr);
}
return {'$or': orExpr};
}
It would build an expression like this:
{"$or":[{"status":32},{"profile":{"$exists":false}}]}
So:
db.collection.find(build_logic_or(myjson))

Related

How to compare the content of 2 columns in functions on object?

I am trying to build a query to match two columns and I have tried the following:
obj= obj.filter(e => e.colOne.exactMatch(e.colTwo))
I am not be able to get this working, is there any way to filter by comparing the content of 2 columns?
The filter() method can't dynamically grab the value to filter based on each object, but can be used to filter on a static value.
You can filter a smaller object set (<100K rows) named myUnfilteredObjects of type ObjectType this way:
let myFilteredObjects = new Set<ObjectType>();
for (const unfilteredObj of myUnfilteredObjects) {
if (unfilteredObj.colOne === unfilteredObj.colTwo) {
myFilteredObjects.add(unfilteredObj);
}
}
Edit: updating with a solution for larger-scale object sets:
You can create a new boolean column in your object's underlying dataset that is true if colOne and colTwo match, and false otherwise. Filtering on this new column via the filter() method will then work as you expect.
It is not possible to compare two columns when writing Functions. A recommended strategy here would be to create a new column that captures your equality. For example in your pyspark pipeline, right before you generate the end objects that get indexed:
df.withColumn("colOneEqualsColTwo", F.when(
F.col("colOne") == F.col("colTwo"), True
).otherwise(False)
And then filter on that new column:
obj = obj.filter(e => e.colOneEqualsColTwo.exactMatch(true))

Cypress: assertion error on json field comparison

i am trying to do assertion on a json. basically i have to compare two json:
cy.get('h4#idParameters').each(($e, index, $list) => {
const text = $e.text()
expect(text).to.eq(parameters)
})
but I get the following error:
in the assertion if I use "contain" instead of "eq" the result doesn't change
There exist a space after ":" char in the first parameter. These strings are not equal.
If you want to compare this as a string, ensure it does not have extra spaces, points, or is in a different order.
But the better approach is to compare as JSON. One interesting approach should be using the deep-equal-in-any-order plugin. This plugin compares objects independent of it order. But first ensure to transform JSON strings to objects.
in the end I solved it like this. Thanks for the advice #Erme.
cy.get('h4#idParameters').each(($e, index, $list) => {
const text = $e.text()
var p1 = JSON.stringify(text)
var p2 = JSON.stringify(parameters)
p1=p1.replace(/\s/g, '');
p2=p2.replace(/\s/g, '');
p2 = p2.substr(1,p2.length)
expect(p1).to.contain(p2)
})

store string into array

In MySQL, I have a field name postcodes and the type is LONGTEXT. It stores several postcodes being separated by comma. How would I retrieve that and store it as an array for other use ?
you can use the PHP method explode().
one think you can't do, is to do a where x = x on it in the database.
In the model, you can set the mutator methods:
public function getPostcodesAttribute($value) {
return explode(',',$value);
}
public function setPostcodesAttribute($value) {
$this->attributes['postcodes'] = implode(',',$value);
}
Lets say that you have the result stored in a string like this:
$s = "6000,5447"; //$s = $array->postcodes;
you can get the each value on an index in an array using this:
$values= explode(",", $s);
echo $values[0]; // 6000
Or even better.. you can store it as json, and retrieve it as json in array format.
Store it as a JSON field in MySQL, Laravel encode and decode them when you retrieve and save them respectively
in your migration
$table->json('field_name');
then in the model
protected $json = ['field_name'];
then whenever you access the field, laravel will convert it to an array for you, you don't have to call any explicit methods.
Doc - https://laravel.com/docs/5.7/eloquent-mutators#attribute-casting
// the final array all the post codes are collected.
$postCodes = [];
foreach (Model::pluck('postcodes') as $stringCodes)
foreach (explode(',', $stringCodes) as $postCode) $postCodes[] = $postCode;

LINQ for SQL statement that returns single scalar value

I want to execute the following select:
SELECT 0 as Value
What is the correlating syntax in LINQ for SQL?
Edit
I want to use the correlating LINQ for SQL statement in a Concat() call like this
var c = (from a in mytable select a.Value).Concat(select 0).Sum();
As you can see, Concat(select 0) obviously doesn't compile. Any ideas?
Edit 2
David suggested to use a simple collection instead. I've tried
private decimal[] mZeroDecimals = new[] { 0.0m };
...
public void MyFunction()
{
var c = (from a in mytable select a.Value).Concat(mZeroDecimals).Sum();
...
but it throws an exception Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator.
You're not actually querying anything, so there is no LINQ involved. You're just creating an anonymous object with a single property called Value:
var obj = new { Value = 0 };
Edit: Based on your comment, it sounds like you want this object in a collection. That doesn't make it a LINQ query (since you're still not querying anything), but you can declare a collection just as easily as a single object. Something like this:
var coll = new[] { new { Value = 0 } };
Since this is a collection, it can be used with any of the enumerable extension methods that LINQ uses, which sounds like what you're trying to do.

Get SQL array from ActiveRecord::Relation

I'm building up a query like this:
scope = User.select(:name).where("name = ?", 'test')
In another part of my code, I'm trying to convert scope, which is an ActiveRecord::Relation object into a SQL array like ["SELECT name FROM users WHERE name = ?", 'test']. Is there any way to accomplish this? Thanks in advance.
It doesn't appear to be possible to get the array you want back from an ActiveRecord::Relation object.
Say that we're just using where. When we call User.where("name = ?", "test") we enter the where method in ActiveRecord::QueryMethods. This calls where! which calls build_where. Since we passed in the query as a String we end up here:
# ActiveRecord::QueryMethods#build_where
when String, Array
[#klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
sanitize_sql combines the SQL query with the values and the result is stored in where_values:
> User.where("name = ?", "test").where_values
=> ["name = 'test'"]
ActiveRecord::Relation only holds onto this combined version, not the query and values separately.