While trying to update a dictionary inside the iterator I got the error "SyntaxError: expected expression, got keyword 'if'"
The ut_frequencies data looks like:
{ "_id" : "app1", "cnt" : 3422 }
{ "_id" : "app2", "cnt" : 2752 }
{ "_id" : "app3", "cnt" : 2736 }
{ "_id" : "app4", "cnt" : 2711 }
Which I suppose is a list of dictionaries. I want to check if the app is already in the data dictionary and if so, update the "utf" value, if not, then add a new item only with the "utf" attribute set.
ut_frequencies.forEach(item=>
if(item._id in data){
data[item._id]["utf"] = item.cnt;
}else{
data[item._id] = {utf: item.cnt, atf: 0, ptf: 0};
}
)
Which is the best way to solve this.
The problem is that on the right of the arrow, an expression is expected.
An if condition is not an expression, therefore you should put braces around the body of the function.
ut_frequencies.forEach(item => {
if(item._id in data){
data[item._id]["utf"] = item.cnt;
}else{
data[item._id] = {utf: item.cnt, atf: 0, ptf: 0};
}
});
Related
I am trying to update a document in Mongo if it has a certain value within a field.
{
"_id" : ObjectId("myObject"),
"source" : "BW",
"sourceTableName" : "myTable",
"tableName" : "tier",
"type" : "main",
"fieldMappings" : [
{
"sourceField" : "tier_id", <~~~~ If this is "tier_id", I want to change it to "trmls_id"
"reportingField" : "bw_id",
"type" : "integer",
"defaultMap" : {
"shouldErrorOnConvert" : false
}
}
]
}
I tried something like
db.getCollection('entityMap').update({"sourceTableName":"myTable"}, {"fieldMappings.0.sourceField":"trmls_id":{$exists : true}}, { $set: { "fieldMappings.0.sourceField": "tier_id" } })
and I think it is failing on the $exists parameter I am setting.
Is there a more cleaner/dynamic way to do this?
The whole query I am trying to formulate is
In the table myTable
I want to check if there is a sourceField that has the value tier_id
If there is tier_id, then change it to trmls_id
Otherwise do nothing
If there is a similar StackOverflow question that answers this, I am happy to explore it! Thanks!
There is a syntax mistake and you can use positional operator $ in update part because you have already selector field in query part,
db.getCollection('entityMap').update(
{
"sourceTableName": "myTable",
"fieldMappings.sourceField": "tier_id" // if this field found then it will go to update part
},
{
$set: {
"fieldMappings.$.sourceField": "trmls_id"
}
}
)
I have a document in my collection:
{
"_id" : ObjectId("5b8aaaebf57de10e080c9151"),
"user_email" : "temp#temp.com",
"platforms_budget" : [
{
"_id" : ObjectId("5b8aaaebf57de10e080c9154"),
"platform_id" : "f_01",
"platform_name" : "Facebook"
},
{
"_id" : ObjectId("5b8aaaebf57de10e080c9153"),
"platform_id" : "i_01",
"platform_name" : "Instagram"
},
{
"_id" : ObjectId("5b8aaaebf57de10e080c9152"),
"platform_id" : "f_02",
"platform_name" : "Facebook_Adds"
}
],
"__v" : 0
}
I want to find specific user by "user_email" and get the length of the relevant "platform_budget" array. Which in this case suppose to be length=3.
My function is like this:
var BudgetSchema = require('../models/Budget');
router.post('/temp', async function (req, res) {
var length = await BudgetSchema.aggregate(
[{ $match: { user_email: "test#test.com" } }, { $unwind: "$platforms_budget" },
{ $project: { "platforms_budget.count": { $size: '$platforms_budget' } } }])
console.log(length);
})
When I try to console.log(length) I get an empty array.
I saw other answers on stackoverflow like this one, but I still can't understand what am I doing wrong or how to extract the size from the responce.
How do I get "platforms_budget" array size?
Thank you.
Assuming that ../models/Budget exports a Model, the Model#aggregate(Array, Function) expects the pipeline with aggregations as an array and an optional callback function that is passed an error (if any) and the result (if any).
.aggregate([...], function(error, resource) {
// do what you want here
});
Or what you can also do is use the Aggregate object itself and invoke .exec(Function) on it where the function is a callback as well.
.aggregate([...]).exec(function(error, resource) {
// do what you want here
});
I personally am still a bit confused about the documentation of .aggregate(Array, Function).
If a callback is passed, the aggregate is executed and a Promise is returned. If a callback is not passed, the aggregate itself is returned.
It sounds like if a callback is passed a promise is still returned but I couldn't find any evidence of any promise being returned by .aggregate(Array, Function) on GitHub at all.
When I perform a single search request with aggregations it works fine. But when I try to perform a multisearch request, aggregations don't seem to work. Isn't it supposed to?
Below is my code, am I doing something wrong (the output is list of hits and no aggregations)? or is msearch not support aggs?
var body = {
"query": {
"filtered" : {
"filter" : {
"and" : filterObj.filters
}
}
}
};
var bodyArray = [];
for (var aggItem in multiaggregations){
bodyArray.push({ "index" : "myindex", "size" : 0});
bodyArray.push({ "query": body.query, "aggregations": aggItem});
}
client.msearch({
body: bodyArray
});
I've posted the following question which has been answered correctly:
MongoDB - Updating only $ref from DBRef field type
Despite of this when I execute the find method like this:
{ "codeId" : { "$ref" : "code" , "$id" : { "$oid" :
"4ff1c08c6ef25616ce21c4b6"}} }
The document isn't returned... Any idea why?
After the update the document is stored like this:
{ "_id" : { "$oid" : "5097ae1cd3159eb52d05574c"} , "codeId" : { "$ref"
: "code" , "$id" : { "$oid" : "4ff1c08c6ef25616ce21c4b6"}} }
By the way, using uMongo GUI, if I select the Update option over this stored document, and save it, without making any changes whatsoever, and then make the find query once again, the document is returned by the query...
Thanks
This is a clearly one of those DBRef "tweaky" things...
As a temporary (but probably correct) fix, I managed to solve this problem executing this javascript procedure:
var cursor = db.menu.find( { "codeId.$ref" : "version" } );
while( cursor.hasNext() )
{
var document = cursor.next();
db.menu.update(
document,
{ $set: {"codeId" : DBRef("code", document.codeId.$id) }},
{ upsert: false, multi: true }
);
}
Still, I won't consider this to be the best way to achieve what I want... Any other solution that involves less lines?
Does anyone know how I can update in MongoDB.
I want to update the totalVisits with timesvisted
// Test data
var currentUser = "John"
var currentPage = "pageName"
var timesvisited = 59
Page.find({"_id" : currentUser}, [], {},function(err, pages) {
pages = pages.map(function(ud) {
return { userDetails: ud};
});
//database structure example
{ "_id" : "John",
"pageName" : { "totalVisits" : 58,
"timeOnPage" : 2432,
"lastVisitDate" : "10/11/2011",
"clickNoOnPage" : "5"
},
"anotherPageName" : { "totalVisits" : 18,
"timeOnPage" : 5362,
"lastVisitDate" : "01/10/2011",
"clickNoOnPage" : "15"
I am trying to update the totalVisits value and have tried something like
{$set : { pages[0].userDetails[currentPage].totalVisits : timesvisted}}
However I get a "SyntaxError: Unexpected token [" message
One of the problems I am having is with the [currentPage] section as currentPage can change so I can not hard code the pageName in.
Edit ***
I have modified this line
lastVisitedSiteDate = {$set : { "pageName.totalVisits" : timesvist}};
and this works fine. However, I need the pageName not to be hard coded in, its needs to be something like currentPage so different page names can be passed into it e.g. anotherPageName.
The second parameter to Mongo's find function specifies which fields to pull back. It needs to be a document, as in {}, not an array.