How to change array elements - mongodb

How to write correct this part of query:
parseFloat(data.versions.0.content.axdducvoxb) ?**
I try to change my fields type from string to float. I have a lot of documents with main element and history of same elements:
axdducvoxb
versions.0.content.axdducvoxb
versions.1.content.axdducvoxb
versions.2.content.axdducvoxb
.......
Code:
db.documents.find().forEach(function(data) {
db.documents.update({_id:data._id},
{$set: {axdducvoxb:parseFloat(data.axdducvoxb)}});
})
When I use it everything is OK:
db.documents.find({"type": "chair"}).forEach(function(data) {
db.documents.update({_id:data._id},
{$set:{'versions.0.content.axdducvoxb':
parseFloat(data.axdducvoxb)}});
})
When I use it I replace versions.0.content.axdducvoxb element to data.axdducvoxb element
But when I make correct replace I see the Error:
SyntaxError: Unexpected number
Code:
db.documents.find({"type": "chair"}).forEach(function(data) {
db.documents.update({_id:data._id},
{$set:{'versions.0.content.axdducvoxb':
parseFloat(data.versions.0.content.axdducvoxb)}});
})
data.versions[0].content.axdducvoxb does not work too

Related

ParseSwift ParseObject QueryConstraint

I have two collections in a mongo DB.
Here is how a document looks in the first collection (MainCollection):
_id
:"mzWqPEDYRU"
TITLE
:"ZAZ: I want."
ownerID
:"lGutCBY52g"
accessKey
:"0kAd4TOmoK0"
_created_at
:2020-03-13T11:42:11.169+00:00
_updated_at
:2020-03-13T17:08:15.090+00:00
downloadCount
:2
And here is how it looks in the second collection (SecondCollection):
_id
:"07BOGA8bHG"
_p_unit
:"MainCollection$mzWqPEDYRU"
SENTENCE
:"I love nature peace and freedom."
Order
:5
ownerID
:"lGutCBY52g"
AUDIO
:"07067b5589d1edd1d907e96c1daf6da1_VOICE.bin"
_created_at
:2020-03-13T11:42:17.483+00:00
_updated_at
:2020-03-13T11:42:19.336+00:00
There is a parent children relationship between the first and the second collection. In the last document we can see the _p_unit field where the "mzWqPEDYRU" part points to the id of the parent in the first collection.
I have one problem from start with the following code:
func theFunction() {
do {MainCollection.query().find() {
result in
switch result {
case .success(let items):
print("items.count = \(items.count)")
for item in items {
/// ....
}
case .failure(let error):
print("Error in \(#function): \(error)")
}
}
}
}
The way this above code is written works fine and I get the number of elements in MainCollection as one would expect. But then comes a less expected behaviour, in this same code if I replace MainCollection by SecondCollection, instead of getting the number of elements in SecondCollection as I would think. I get an error like:
ParseError(code: ParseSwift.ParseError.Code.unknownError,
message: "Error decoding parse-server response:
Optional(<NSHTTPURLResponse: 0x2837211a0> { URL:}
{ Status Code: 200, Headers {} }) with error:
The data couldn’t be read because it isn’t in the correct format.
Format: Optional(\"{\\\"results\\\": .......
Can anybody point out what is causing this?
It is something like:
var SecondCollection.query(unit == documentOne).find()
The .query() method works in a key/value scheme so it should pass the key as a string and the value as the referenced type, so passing "unit" between double quotes is correct:
do {SecondCollection.query("unit" == cell).find() {
The error you're getting is because cell is a Parse.Object and it is expecting a value in that place (a property in this case).
Please try the following and see if it works for you:
do {SecondCollection.query("unit" == cell.id).find() {

Mongo : Custom system.js in find(), like query

trying to write a Mongo query that will Base64 Decode a field that is Base64 encoded and then perform a simple "like" on the decoded value. I'm following a couple of different posts as well as the Mongo docs, but can't seem to get the syntax correct. I basically want to do a query like this :
db.getCollection('my-collection').find (
{ base64Decode(edmDocumentId): /ni-billing-retro/ }
);
Where base64Decode() is a custom function inserted into system.js.
Posts:
----------------
Export text stored as Bindata in mongodb
How to query MongoDB with "like"?
What I've done so far :
I saved the base64Decode() function to the system.js, and I can see the function....https://docs.mongodb.com/manual/tutorial/store-javascript-function-on-server/.
db.system.js.insertOne( {
_id: "base64Decode",
value : function (s) {
var e={},i,k,v=[],r='',w=String.fromCharCode,u=0;
var n=[[65,91],[97,123],[48,58],[43,44],[47,48]];
for(z in n){for(i=n[z][0];i<n[z][1];i++){v.push(w(i));}}
for(i=0;i<64;i++){e[v[i]]=i;}
function a(c){
if(c<128)r+=w(c);else if(c>=192)u=c;else r+=w(((u&31)<<6)+(c&63));
}
for(i=0;i<s.length;i+=72){
var b=0,c,x,l=0,o=s.substring(i,i+72);
for(x=0;x<o.length;x++){
c=e[o.charAt(x)];b=(b<<6)+c;l+=6;
while(l>=8)a((b>>>(l-=8))%256);
}
}
return r;
}
});
I've tried using $where, to no avail...returns ReferenceError: edmDocumentId is not. Added the db.loadServerScripts(); to fix the base64Decode() Reference error.
db.loadServerScripts();
db.getCollection('rapid-document-meta').find (
{ $where: (base64Decode(edmDocumentId) == /ni-billing/) }
);
I've tried doing a straight find (), Unexpected token : Line 2
db.getCollection('rapid-document-meta').find (
{ base64Decode(edmDocumentId): /ni-billing-retro/ }
);
Tried the following from Calling db.system.js Function in $where : ReferenceError: edDocumentId is not defined, even though edmDocumentId is on every single record.
db.loadServerScripts();
db.getCollection('rapid-document-meta').mapReduce (
base64Decode(edDocumentId),
function() {},
{ "out": { "inline": 1 } }
);
Does someone have an example of a find query that uses a custom function from system.js??? Mongo version 4.0.8.

POSTGRES check if a provided value is present in the column of type array

I am trying to check whether a value if present in the column, which is of type array(column_name text[]).
As a server i am using hapi and trying to check the same from hapi through query.
Query which i have written is(query is not working):
where: { column_name: { $in: { provided_value} }}
The column contains the values as:
{1234, 3456}
The values are of type text.
Can someone please help me to identify the issue.
Thanks in advance.
Sequelize does not support this use of ANY, they seem to only support its use like IN.
Instead, you should try the contains operator (#>):
import {Op} from "sequelize";
MyModel.findAll({
where: {
column_name: {
[Op.contains]: [provided_value]
}
}
});
This will generate something like
SELECT * FROM "MyModel" WHERE column_name #> '{"provided_value"}';

Apollo query array within an array

Return from Server
In Apollo I can query down about two levels and then I get "returns undefined". I can get down to "project" on line 7, But I cannot get "Checklists" on line 12. Any help would be greatly appreciated.
updateNotication(){
this.apollo
.watchQuery({
query: gql`
query
{
project
(id:[2272],accesstoken:"val")
{
ID,
Title,
Checklists
{
ID,
Name,
DateDue
}
}
}
`,
})
.valueChanges.subscribe((result: ApolloQueryResult<any> ) => {
console.log('data', result.data); // returns data Object
console.log('project', result.data.project); // returns project array
console.log('Checklists', result.data.project.Checklists); // returns undefined
});
}
result.data.project is an Array. If you want to get the property of one of the arrays items, you need to do something like:
result.data.project[0].Checklists

Update nested array object (put request)

I have an array inside a document of a collection called pown.
{
_id: 123..,
name: pupies,
pups:[ {name: pup1, location: somewhere}, {name: pup2, ...}]
}
Now a user using my rest-service sends the entire first entry as put request:
{name: pup1, location: inTown}
After that I want to update this element in my database.
Therefore I tried this:
var updatedPup = req.body;
var searchQuery = {
_id : 123...,
pups : { name : req.body.name }
}
var updateQuery = {
$set: {'pups': updatedPup }
}
db.pown.update(searchQuery, updateQuery, function(err, data){ ... }
Unfortunately it is not updating anythig.
Does anyone know how to update an entire array-element?
As Neil pointed, you need to be acquainted with the dot notation(used to select the fields) and the positional operator $ (used to select a particular element in an array i.e the element matched in the original search query). If you want to replace the whole element in the array
var updateQuery= {
"$set":{"pups.$": updatedPup}
}
If you only need to change the location,
var updateQuery= {
"$set":{"pups.$.location": updatedPup.location}
}
The problem here is that the selection in your query actually wants to update an embedded array element in your document. The first thing is that you want to use "dot notation" instead, and then you also want the positional $ modifier to select the correct element:
db.pown.update(
{ "pups.name": req.body.name },
{ "$set": { "pups.$.locatation": req.body.location }
)
That would be the nice way to do things. Mostly because you really only want to modify the "location" property of the sub-document. So that is how you express that.