How to update jarray in jsonb field? - postgresql

I have a jsonb field that contained the something like below:
How to update is_read properties in extras node to true where the users_pid = 1 and is_read=false?
I have tried below:
UPDATE chats
SET attributes = jsonb_set(
cast(attributes->'data'->>'extras' AS jsonb),
array['is_read'],
to_jsonb(true)
)
WHERE users_pid =1
AND cast(attributes->'data'->'extras_to'- >>'is_read' AS boolean) = false
but nothing updated
[
{
"data": {
"users_pid": 1,
"datetime": "2022-05-01 13:10:58",
"extras": {
"is_read": false,
"read_dt": ""
}
}
},
{
"data": {
"users_pid": 3,
"datetime": "2022-05-23 11:03:22",
"extras": {
"is_read": false,
"read_dt": ""
}
}
},
{
"data": {
"users_pid": 1,
"datetime": "2022-05-13 11:23:22",
"extras": {
"is_read": false,
"read_dt": ""
}
}
}
]

Related

MongoDB update a specific nested field

Hi I am trying to update nested filed , but couldn't able to do so.
Here is the sample data,
[{
"_id": {
"$oid": "632ec4128f567511dcd80ed9"
},
"company_id": 1,
"contact_id": 1001,
"roles_to_be_accepted": {
"ROLE#04": {
"assigned_data": {
"assigned_3HFui": {
"is_idle": false,
"send_for_acceptance_date": 1664009233,
"action_date": ""
},
"assigned_b1J9t": {
"is_idle": false,
"send_for_acceptance_date": 1664009233,
"action_date": ""
}
}
},
"ROLE#02": {
"assigned_data": {
"assigned_uPJI1": {
"is_idle": false,
"send_for_acceptance_date": 1664009233,
"action_date": ""
}
}
}
}
}]
Now I want to update that is_idle field to true. I have tried in this way
let query = { contact_id: 1, company_id: 1001};
const db = this.client.db("dbname");
const col= db.collection("collection_name");
col.update(query, {
'$set': { "roles_to_be_accepted.assigned_data.is_idle": true }
});

Sequelize nested include without null properties

using ExpressJs/Postgres/Sequelize and when doing findOne I am getting an object return that contains nested objects with following data in the response:
"CompanyVolume": null,
"CompanyMarkets": [],
Is there a way to avoid receiving these properties with null/[] from Postgres?
Appreciate any thoughts...:)
const kyc = await db.Kyc.findOne({
where: {id: req.params.id},
include: [
{model: db.Company,
include: [
{ model: db.CompanyStakeholder, through: db.Role },
{ model: db.CompanyDelivery,
// where: {
// deliveryAverageDurationAmount: {[Op.not]:null},
// }
//returns Cannot read properties of undefined (reading 'not')
},
{ model: db.CompanyVolume },
{ model: db.CompanyDelivery },
{ model: db.CompanyMarket },
],
nest: true,
})
the response object with properties including null or empty arrays
[
{
"id": 5,
"kycTitle": "KYC1006428",
"kycPasscode": null,
"kycDescription": "The best kyc ever, lorem epsum sanctus vita loca",
"kycStartDate": "2022-01-28",
"kycStatus": null,
"kycConsent": "approved",
"kycConsentDate": "2022-01-27T14:01:39.924Z",
"createdAt": "2022-01-27T13:19:41.649Z",
"updatedAt": "2022-01-27T14:01:39.919Z",
"id_User": 1,
"Company": {
"id": 6,
"companyName": "Niky",
"companyEntityType": null,
"companyVatNumber": "",
"companyRegistrationNumber": "",
"companyPubliclyListed": null,
"companyAddress1": "Pepovej 234",
"companyAddress2": "",
"companyCity": "Dada",
"companyPostCode": "3400",
"companyCountry": "Owner",
"companyPhone": "+21321321231",
"createdAt": "2022-01-27T13:19:41.669Z",
"updatedAt": "2022-01-27T13:19:41.676Z",
"KycId": 5,
"CompanyStakeholders": [], //I don't want this returned
"CompanyDelivery": null, //I don't want this returned
"CompanyVolume": null, //I don't want this returned
"CompanyMarkets": [], //I don't want this returned
},
}
]
The different Associations:
Company.associate = function (models) {
Company.hasOne(models.Contact)
Company.hasOne(models.CompanyDelivery)
Company.hasMany(models.CompanyMarket)
Company.hasMany(models.CompanyPosBilling)
Company.hasMany(models.CompanySettlement)
Company.hasOne(models.CompanySubscription)
Company.hasOne(models.CompanyVolume)
Company.hasMany(models.CompanyWebsite)
Company.belongsTo(models.Kyc)
Company.belongsToMany(models.CompanyStakeholder, {
through: models.Role,
unique: false
})
}
CompanyDelivery.associate = function (models) {
CompanyDelivery.belongsTo(models.Company)
}
CompanyMarket.associate = function (models) {
CompanyMarket.belongsTo(models.Company)
}
Kyc.associate = function (models) {
Kyc.hasOne(models.Company)
}
CompanyStakeholder.associate = function (models) {
CompanyStakeholder.belongsToMany(models.Company, {
through: models.Role,
unique: false
})
}

How to find average using map reduce in MongoDB?

My document is of format:
{
"PItems": {
"Workspaces": [
{
"Key": "Item1",
"Size": 228.399,
"Foo": "bar"
},
{
"Key": "Item2",
"Size": 111.399,
"Bar": "baz"
},
{
"Key": "Item2",
"Size": 636.66,
"Baz": "foo"
}
]
}
}
I need to find the average size of each items from all the documents in the collection. How do I do that?
Expected output:
Item1: 346.12
Item2: 563.58
I have tried the following:
db.Resources.mapReduce(
function() {
this.PItems.Workspaces.forEach(
function(z) {
emit(z.Key, z.Size);
}
);
},
function(item, space) {
var total = 0;
for ( var i=0; i<space.length; i++ )
total += size[i];
return { avg : total/space.length };
},
out: { inline: 1 }
);
I am getting a syntax error: SyntaxError: missing ) after argument list. What am I missing here?

group by properties and sum of values between nested json and array of objects

I have users array with their name,
var users = [{'name':'zulekha'}, {'name':'deepika'}];
I am fetching worklogged by each user from jira APIs. So I am getting object like this.
var worklogResult = {
"issues": [
{
"fields": {
"worklog": {
"worklogs": [
{
"author": {
"name": "zulekha",
},
"timeSpentSeconds": 180
},
{
"author": {
"name": "deepika",
},
"timeSpentSeconds": 210
}
]
}
}
},
{
"fields": {
"worklog": {
"worklogs": [
{
"author": {
"name": "deepika",
},
"timeSpentSeconds": 140
}
]
}
}
},
{
"fields": {
"worklog": {
"worklogs": [
{
"author": {
"name": "zulekha",
},
"timeSpentSeconds": 600,
}
]
}
}
},
{
"fields": {
"worklog": {
"worklogs": []
}
}
}
]
}
Now I want to match worklogResult with users in such a way that I can get following output.
output = [{'name':'zulekha','timeSpentSeconds':780}, {'name':'deepika', 'timeSpentSeconds':350}]
Can anyone suggest me how to achieve this?
use _.flatMap to flat nested objects
_.chain(worklogResult.issues)
.flatMap('fields.worklog.worklogs')
.thru(function(spents) {
return _.map(users, function(user) {
return _.merge(user, {
timeSpentSeconds: _.chain(spents)
.filter(['author.name', user.name])
.map('timeSpentSeconds')
.sum()
.value()
})
})
})
.value()

Finding multiple docs using same id not working, using meteor + react and mongoDB

How do I get the email address of the students in the same class_id, take it as there are more then 2 students in different class in the DB as well?
I have this but it return empty array []
Meteor.users.find({"course_learn_list.$.class_id": {$in: [classId]}},
{field: {"emails.address": 1}}
).fetch()
Collections
{
"_id": "LMZiLKs2MRhZiiwoS",
"course_learn_list": [
{
"course_id": "M8EiKfxAAzy25WmFH",
"class_id": "jePhNgEuXLM3ZCt98"
},
{
"course_id": "5hbwrfbfxAAzy2nrg",
"class_id": "dfbfnEuXLM3fngndn"
}
],
"emails": [
{
"address": "student1#gmail.com",
"verified": false
}
]
},
{
"_id": "JgfdLKs2MRhZJgfNgk",
"course_learn_list": [
{
"course_id": "M8EiKfxAAzy25WmFH",
"class_id": "jePhNgEuXLM3ZCt98"
},
{
"course_id": "5hbwrfbfxAAzy2nrg",
"class_id": "dfbfnEuXLM3fngndn"
}
],
"emails": [
{
"address": "student2#gmail.com",
"verified": false
}
]
}
I think you want:
Meteor.users.find({ "course_learn_list.class_id": classId },
{ "course_learn_list.$": 1, "emails.address": 1 }).fetch()
This should find the first instance in each course_learn_list array where the classId is your classId.
In this case you probably don't need to use a projection to get the right answer. Here's an example of extracting the verified email addresses using only the . operator in the selector:
const ids = ['jePhNgEuXLM3ZCt98', 'some-other-id'];
const emails =
Meteor.users.find({ 'course_learn_list.class_id': { $in: ids } })
.fetch()
.map(user => _.findWhere(user.emails, { verified: true }).address);
This works for me!
Meteor.publish("getMyClassStudents", function(classId) {
console.log("Publish getMyClassStudents")
var self = this
if (self.userId) {
var data = Meteor.users.find({
"course_learn_list.class_id": classId
}, {
"fields": {
"emails.address": 1
}
})
return data
}
else {
return self.ready()
}
})