Retrieving a relationship field in mongodb aggregation - javascript

I am using mongodb aggregation with a collection named files
that has a relationship with another collection named file_upload.
files = {
type: String,
media: { type: Schema.Types.ObjectId, ref: 'file_upload', required: true },
}
file_upoad = {
name: String,
}
This is the query
const data = await strapi.query('files').model.aggregate([
{
$lookup: {
from: "analytics",
localField: "_id",
foreignField: "file_id",
as: "hits",
}
},
{ $unwind: '$hits' },
{ $group: { _id: "$_id", hitsCount: { $sum: 1 } } },
{ $sort: { hitsCount: -1 } },
{ $limit: 1 },
])
my goal is to retrieve the media as part of the result since it is a relationship field, at the moment I get this
[
{
"_id": "61fd74367b6ee77b89bae34d",
"hitsCount": 12
},
{
"_id": "61fd74367b6ee77b89sddfee",
"hitsCount": 8
}
]
expected result
[
{
"_id": "61fd74367b6ee77b89bae34d",
"hitsCount": 12,
"media": {
name:"name1"
}
},
{
"_id": "61fd74367b6ee77b89sddfee",
"hitsCount": 8,
"media": {
name:"name2"
}
}
]

Related

Mongoose, updated nested array

My question is:
How can I query in the nested arrays?
I want to change value in key "likeUp" which is nested inside object in array "usersWhoLiked". Where "usersWhoLiked" is nested in array "comments"
How Can I do that with mongoose ?
Request that I wrote beneath... do not work, but is very similar to answer given in StackOverflow post: Mongoose update update nested object inside an array
This is my request to db with updateOne:
try {
const response = await Comments.updateOne(
{
productId,
comments: { $elemMatch: { usersWhoLiked: { $elemMatch: { userId } } } },
},
{
$set: { 'comments.$[outer].usersWhoLiked.$[inner].likeUp': likes.up },
},
{
arrayFilters: [{ 'outer._id': commentId }, { 'inner._userId': userId }],
}
).exec();
return res.status(201).json({ response });
} catch (err) {
console.log(err);
return res.send(err);
}
This is the collection, that I am trying to update:
{
"_id": {
"$oid": "6307569d2308b78b378cc802"
},
"productId": "629da4b6634d5d11a859d729",
"comments": [
{
"userId": "62f29c2c324f4778dff443f6",
"userName": "User",
"date": "2022.08.25",
"confirmed": true,
"likes": {
"up": 0,
"down": 0
},
"content": {
"rating": 5,
"description": "Nowy komentarz"
},
"_id": {
"$oid": "630756b22308b78b378cc809"
},
"usersWhoLiked": [
{
"userId": "62f29c2c324f4778dff443f1",
"likeUp": true,
"_id": {
"$oid": "6307572d2308b78b378cc80e"
}
},
{
"userId": "62f29c2c324f4778dff443f2",
"likeUp": true,
"_id": {
"$oid": "6307572d2308b78b378cc80c"
}
}
]
}
],
"__v": 0
}
Mongooes schema for comment collection:
const commentSchema = new Schema({
productId: String,
comments: [
{
userId: String,
userName: String,
date: String,
confirmed: Boolean,
likes: {
up: {
type: Number,
default: 0,
},
down: {
type: Number,
default: 0,
},
},
content: {
rating: Number,
description: String,
},
usersWhoLiked: [{ userId: String, likeUp: Boolean }],
},
],
});
I guess the problem is with your arrayFilters operator, because you are trying to filter by field _userId which does not exist:
arrayFilters: [{ 'outer._id': commentId }, { 'inner._userId': userId }],
I managed to update the likeUp value using the following query:
db.collection.update({
_id: ObjectId("6307569d2308b78b378cc802")
},
{
$set: {
"comments.$[user].usersWhoLiked.$[like].likeUp": false
}
},
{
arrayFilters: [
{
"user._id": ObjectId("630756b22308b78b378cc809")
},
{
"like.userId": "62f29c2c324f4778dff443f1"
}
]
})
Try it on MongoDB playground: https://mongoplayground.net/p/XhQMNBgEdhp

MongooseJS: How to remove 1 object inside Array in Array of Objects

Hi MongooseJS experts!
I'm new in MongooseJS, This is my 2nd day of solving this problem but I can't find a working solution to this.
Thank you in advance!
My Delete method
Cart.updateOne(
{ "content.merchantId": req.body.merchantId },
{ $pull: { "content.items._id": req.body.productId } },
{ new: true },
function (error, result) {
if (error) { }
else if (result) { }
}
);
Schema
const CartSchema = new Schema({
customerId: {
type: String,
required: true,
},
content: {
merchantName: {
type: String,
required: true,
},
merchantId: {
type: String,
required: true,
},
items: [],
},
});
Sample JSON
[
{
"content": {
"merchantName": "SAMPLE_MERCHANT_NAME",
"merchantId": "SAMPLE_MERCHANT_ID",
"items": [
{
"_id": "SAMPLE_ID",
"title": "SAMPLE TITLE",
}
]
},
"_id": "618220e83966345ab5d451cd",
"__v": 0
},
]
Error message
Cannot use the part (_id) of (content.items._id) to traverse the element ({items: [{ _id: "SAMPLE_ID", title: "SAMPLE TITLE"}] })
you should use like this
db.collection.update({
"content.merchantId": "SAMPLE_MERCHANT_ID"
},
{
$pull: {
"content.items": {
"_id": "SAMPLE_ID"
}
}
},
{
new:true
},
)
https://mongoplayground.net/p/Ou26tab2mBU

Query to show json responses which are public true inside mongoose aggregate

I have query like this, in which I try to find average of all ratings linked to specific entity. And then return avg rating as an additional field to entity model. Now I want to filter out only those responses in which public field is set to be true.
This is how my query looks like:-
try {
const reviews = await Entity.aggregate([
{
$lookup: {
from: 'reviews',
localField: '_id',
foreignField: 'entityId',
as: 'avgRating',
},
},
{
$addFields: {
avgRating: {
$avg: {
$map: {
input: '$avgRating',
in: '$$this.rating',
},
},
},
},
},
{
$project: {
admin: 0,
createdAt: 0,
updatedAt: 0,
},
},
]);
res.send(reviews);
} catch (e) {
res.status(500).send();
}
the query works fine and gives the following response
{
{...},
{
"_id": "182ehc02031nd013810wd",
"public": false,
"organizations": [
"icnq03d0-2qidc-cq2c"
],
"cities": [
"1234"
],
"name": "test 3",
"__v": 0,
"avgRating": 5
},
{...},
}
I want to add another condition that it should return only those responses in which public is set to true.
I tried to use $filterbut did not work.
How to do this?
public is a document-level field so you need $match instead of $filter:
{ $match: { public: true } }
Mongo Playground
You can also simplify the way you calculate the average:
{
$addFields: {
avgRating: { $avg: 'avgRating.rating' }
}
}
should work

Destructure arrays within the MongoDB aggregation pipeline

I was wondering if it was possible to destructure arrays while I am still in the MongoDB aggregation pipeline which would make my code alot neater.
For example, I have the following aggregation pipeline.
await User.aggregate([
{ $match: { _id: userID } },
{
$project: { chatLogs: 1, username: 1, profilePicURL: 1 },
},
{ $unwind: "$chatLogs" },
{
$lookup: {
from: "users",
let: { recipientID: "$chatLogs.recipientID" },
pipeline: [
{
$match: { $expr: { $eq: ["$_id", "$$recipientID"] } },
},
{ $project: { profilePicURL: 1 } },
],
as: "chatLogs.recipientID",
},
},
]);
This gives the following results when queried:
{
"_id": "5f2ffb54eea9c2180a732afa",
"username": "joe",
"profilePicURL": "/images/profile/default_profile.png",
"chatLogs": {
"recipientID": [
{
"_id": "5f2faf5ad18a76073729f475",
"profilePicURL": "/images/profile/default_profile.png"
}
],
"chat": "5f30b6c3d117441c2abda1ba"
}
}
In my case, because "recipientID" represents a default MongoDB id, it will always be unique. Hence I would prefer the following, where the resulting recipientID field is no longer a meaningless array
Desired results:
{
"_id": "5f2ffb54eea9c2180a732afa",
"username": "joe",
"profilePicURL": "/images/profile/default_profile.png",
"chatLogs": {
"recipientID": {
"_id": "5f2faf5ad18a76073729f475",
"profilePicURL": "/images/profile/default_profile.png"
}
"chat": "5f30b6c3d117441c2abda1ba"
}
}
You can deconstruct recipientID array using $unwind in last pipeline,
await User.aggregate([
... // your all pipelines
// add this line
{ $unwind: "$chatLogs.recipientID" }
]);

Convert Date to String in nested array in mongodb

I have a mongodb collection called cases and inside cases I have an array of cases per company object.
So the structure is:
Inside each case I want to use the createddate (which is a string) and endDate (also string) and convert it to a mongodb date.
When I use NoSQLBooster I add the following query:
db.cases.aggregate([
{ $match: { companyID: 218 }},
{ $unwind: "$cases" },
{ $match: { 'cases.id': '299' }},
{ $addFields: { 'cases.created': new Date('2010-06-21T00:00:00.000'), 'cases.closed': new Date('2014-08-29T00:00:00.000') }},
{ $group: { _id: "$_id", cases: { $push: "$cases" }}}])
This will add a date in a new field - created and then closed. This is exactly what I want.
However, in my code (using mongoose) I have the following:
scripts.commponent.ts:
runThroughCasesAndConvertDates(id) {
this.scriptsService.getAllCasesToModify({ companyID : id}).subscribe( res => {
if (res.length > 0) {
for (let i = 0; i < res[0].cases.length; i++) {
const caseID = res[0].cases[i].id;
const data = {
companyID: id,
caseID: caseID,
created: moment(res[0].cases[i].createddate, 'DD-MMM-YYYY h:mm a').format('YYYY-MM-DD[T00:00:00.000Z]'),
closed: ''
};
if (res[0].cases[i].endDate !== '') {
data.closed = moment(res[0].cases[i].endDate, 'DD-MMM-YYYY h:mm a').format('YYYY-MM-DD[T00:00:00.000Z]');
}
this.scriptsService.updateDates(data).subscribe();
}
}
});
}
scripts.service.ts
updateDates(body) {
return this.http.post('/db/cases/updateAllDates', body).pipe(
map(res => res.json())
);
}
casesDB.js
router.post('/updateAllDates', (req, res) => {
const { body } = req;
Cases.aggregate([
{ $match: { companyID: body.companyID }},
{ $unwind: "$cases" },
{ $match: { 'cases.id': body.caseID }},
{ $addFields: { 'cases.created': new Date(body.created), 'cases.closed': new Date(body.closed) } },
{ $group: { _id: "$_id" }
}],
function (err, data) {
res.json(data)
});
});
But it does not add anything into the array. Im really confused as to what Im doing wrong. Maybe there is a better way / approach to doing this?
Thank you
You can $map over the cases array and can change the date string fields to date object fields.
Cases.aggregate([
{ "$addFields": {
"cases": {
"$map": {
"input": "$cases",
"in": {
"$mergeObjects": [
"$$this",
{
"createddate": {
"$dateFromString": { "dateString": "$$this.createddate" }
},
"endDate": {
"$dateFromString": { "dateString": "$$this.endDate" }
}
}
]
}
}
}
}}
])
Update: If dates are blank string
Cases.aggregate([
{ "$addFields": {
"cases": {
"$map": {
"input": "$cases",
"in": {
"$mergeObjects": [
"$$this",
{
"createddate": {
"$cond": [
{ "$eq": ["$$this.createddate", ""] },
null
{ "$dateFromString": { "dateString": "$$this.createddate" } }
]
},
"endDate": {
"$cond": [
{ "$eq": ["$$this.endDate", ""] },
null
{ "$dateFromString": { "dateString": "$$this.endDate" } }
]
}
}
]
}
}
}
}}
])

Categories

Resources