How to use aggregation with nested document? - node.js

I'm new to mongoose, I'm confuse while create the query. Can you help me?
I have a movie document like this :
"movies": [
{
"id": "635611395a71beb6c5bf0b4d",
"title": "Mission: Impossible - Fallout",
"createdAt": "2022-10-24T04:14:54.445Z",
"cast": [
{
"actor": "635350c581d5b60383f0c4be",
"roleAs": "Ethan Hunt",
"leadActor": true,
"_id": "635658c18b9e50facd7f1fd1"
},
{
"actor": "63560bf55a71beb6c5bf0b1f",
"roleAs": "Ilsa Faust",
"leadActor": false,
"_id": "635658c18b9e50facd7f1fd2"
}
],
"poster": {
"url": "https://res.cloudinary.com/debfn35m1/image/upload/v1666603204/vczxb7lgbonjn8ydsyep.jpg",
"public_id": "vczxb7lgbonjn8ydsyep",
"responsive": [
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_640/v1666603204/vczxb7lgbonjn8ydsyep.jpg",
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_50/v1666603204/vczxb7lgbonjn8ydsyep.jpg"
]
},
"reviews": {
"ratingAvg": "5.0",
"reviewCount": 2
}
},
{
"id": "635614855a71beb6c5bf0bdc",
"title": "Spider-Man: No Way Home",
"createdAt": "2022-10-24T04:28:58.286Z",
"cast": [
{
"actor": "635350a881d5b60383f0c4b8",
"roleAs": "Peter Parker",
"leadActor": true,
"_id": "636a2d6520cf4cf14a11ef95"
},
{
"actor": "635611eb5a71beb6c5bf0b99",
"roleAs": "MJ",
"leadActor": false,
"_id": "636a2d6520cf4cf14a11ef96"
}
],
"poster": {
"url": "https://res.cloudinary.com/debfn35m1/image/upload/v1667902823/tajzr9hpulvzqoytgpxu.jpg",
"public_id": "tajzr9hpulvzqoytgpxu",
"responsive": [
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_640/v1667902823/tajzr9hpulvzqoytgpxu.jpg",
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_470/v1667902823/tajzr9hpulvzqoytgpxu.jpg",
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_50/v1667902823/tajzr9hpulvzqoytgpxu.jpg"
]
},
"reviews": {
"ratingAvg": "8.0",
"reviewCount": 2
}
},
This is my desired result:
{
"id": "635611395a71beb6c5bf0b4d",
"title": "Mission: Impossible - Fallout",
"createdAt": "2022-10-24T04:14:54.445Z",
"cast": [
{
"actor": "635350c581d5b60383f0c4be",
"roleAs": "Ethan Hunt",
"leadActor": true,
"_id": "635658c18b9e50facd7f1fd1"
},
{
"actor": "63560bf55a71beb6c5bf0b1f",
"roleAs": "Ilsa Faust",
"leadActor": false,
"_id": "635658c18b9e50facd7f1fd2"
}
],
"poster": {
"url": "https://res.cloudinary.com/debfn35m1/image/upload/v1666603204/vczxb7lgbonjn8ydsyep.jpg",
"public_id": "vczxb7lgbonjn8ydsyep",
"responsive": [
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_640/v1666603204/vczxb7lgbonjn8ydsyep.jpg",
"https://res.cloudinary.com/debfn35m1/image/upload/c_scale,w_50/v1666603204/vczxb7lgbonjn8ydsyep.jpg"
]
},
"reviews": {
"ratingAvg": "5.0",
"reviewCount": 2
}
},
Im trying to write a filter function to get all movie that has Tom Cruise with actorId as a parameter but cannot get the result.
Can someone please help me with this ?

Since your actor id is inside a cast array with key actor you must specify your key while match, check the updated code below
exports.actorAggregation = (actorId) => {
return [
{
$lookup: {
from: "Movie",
localField: "cast",
foreignField: "_id",
as: "actorFilter",
},
},
{ $unwind: "$cast" },
{
$match: {
"cast.actor._id": { $in: [actorId] }, // or "cast.actor": { $in: [actorId] },
status: { $eq: "public" },
},
},
{
$project: {
title: 1,
poster: "$poster.url",
responsivePosters: "$poster.responsive",
createdAt: "$createdAt",
},
},
];
};

Related

How to only update one match of an array filter in mongodb

Problem:
I need to only update one document in the spots available array that has an id of "empty". My previous query was updating all matching sub documents with "empty" as the id; which is no good Example Below. So I decided to use aggregation so that I could add a limit stage so that I could only update one item, but come to find out I cannot update the original document with an aggregation. This leaves the only option to use an array filter that only updates one/first of its matches. Is this possible? I feel like there has to be a way to only update one match on an array filter and if there isn't this is definitely something that should be added.
My code:
This code updates every object with "empty"
const client = await clientPromise;
const db = client.db();
// const query = db.collection('events').aggregate(agg);
const query = await db.collection('events').updateOne({
_id: new ObjectId("6398c34ca67dbe3286452f23"),
createdBy: new ObjectId("636c1778f1d09191074f9690"),
"weights.weight": 12
},
{
$set: {
"weights.$.spotsAvailable.$[el2]": {
"name": "Wayne Wrestler",
"userId": new ObjectId("636c1778f1d09191074f9690")
}
}
},
{
arrayFilters: [{ "el2": { "userId": "empty" } }]
})
Example documents:
Event:
{
"_id": {
"$oid": "6398c34ca67dbe3286452f23"
},
"name": "test",
"createdBy": {
"$oid": "636c1778f1d09191074f9690"
},
"description": "testing",
"date": {
"$date": {
"$numberLong": "1645488000000"
}
},
"location": {
"type": "Point",
"coordinates": [
0,
0
]
},
"weights": [
{
"spotsAvailable": [
{
"name": "empty",
"userId": "empty"
},
{
"name": "empty",
"userId": "empty"
},
{
"name": "empty",
"userId": "empty"
}
],
"weight": 12
},
{
"spotsAvailable": [
{
// only one of these should've been updated, but both were
"name": "Wayne Wrestler",
"userId": {
"$oid": "636c1778f1d09191074f9690"
}
},
{
"name": "Wayne Wrestler",
"userId": {
"$oid": "636c1778f1d09191074f9690"
}
}
],
"weight": 15
}
],
"eventApplicants": [
{
"userId": {
"$oid": "636c1778f1d09191074f9690"
},
"name": "Wayne Wrestler",
"weight": 12
}
]
}
User:
{
"_id": {
"$oid": "636c1778f1d09191074f9690"
},
"name": "Wayne Wrestler",
"email": "wakywayne80#gmail.com",
"image": "https://lh3.googleusercontent.com/a/ALm5wu32gXjDIRxncjjQA9I4Yl-sjFH5EWsTlmvdM_0kiw=s96-c",
"emailVerified": {
"$date": {
"$numberLong": "1670864727212"
}
},
"createdEvents": [
{
"createdEventName": "test",
"createdEventDate": {
"$date": {
"$numberLong": "1645488000000"
}
},
"createdEventDescription": "testing",
"createdEventWeights": [
{
"weight": "12",
"filled": [
false,
false,
false
]
},
{
"weight": "15",
"filled": [
false,
false
]
}
],
"createdEventId": {
"$oid": "6398c34ca67dbe3286452f23"
}
}
],
"userSignedUpEvents": [],
"availableWeights": [
1,
123
],
"signedUpEvents": [
{
"eventId": {
"$oid": "636c722f67642c30dc5ffc30"
},
"eventName": "Utah",
"eventDate": {
"$date": {
"$numberLong": "1667913330000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "636c722f67642c30dc5ffc30"
},
"eventName": "Utah",
"eventDate": {
"$date": {
"$numberLong": "1667913330000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "637ec484ac2d675b30590b47"
},
"eventName": "Maybe?",
"eventDate": {
"$date": {
"$numberLong": "1672272000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "636c722f67642c30dc5ffc30"
},
"eventName": "Utah",
"eventDate": {
"$date": {
"$numberLong": "1667913330000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "638d5274628db2a7bf61df49"
},
"eventName": "Eva's",
"eventDate": {
"$date": {
"$numberLong": "1698019200000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "636c722f67642c30dc5ffc30"
},
"eventName": "Utah",
"eventDate": {
"$date": {
"$numberLong": "1667913330000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398a922abb5c168ede595fb"
},
"eventName": "Nikko's event",
"eventDate": {
"$date": {
"$numberLong": "1670976000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398a922abb5c168ede595fb"
},
"eventName": "Nikko's event",
"eventDate": {
"$date": {
"$numberLong": "1670976000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398c34ca67dbe3286452f23"
},
"eventName": "test",
"eventDate": {
"$date": {
"$numberLong": "1645488000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398c34ca67dbe3286452f23"
},
"eventName": "test",
"eventDate": {
"$date": {
"$numberLong": "1645488000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398c34ca67dbe3286452f23"
},
"eventName": "test",
"eventDate": {
"$date": {
"$numberLong": "1645488000000"
}
},
"accepted": false
},
{
"eventId": {
"$oid": "6398c34ca67dbe3286452f23"
},
"eventName": "test",
"eventDate": {
"$date": {
"$numberLong": "1645488000000"
}
},
"accepted": false
}
]
}
I have tried:
Pluging in variables without the new ObjectId syntax
Plugin in variables with the new ObjectId syntax
Using the exact same hardcoded values that I got from copying the aggregation code from compass for the node driver
All of these either don't work or result in every subdocument with "empty" getting filled
One option is to use update with pipeline:
Since this is a double nested array, it is easier to do it in two steps - internal and external
First create the "external" item to replace in weights array and call it newItem. It is calculated using $reduce which allow us to manipulate the internal array while looping on it.
Replace the relevant item on weights array with our newItem using $map with $cond
db.collection.update(
{_id: ObjectId("6398c34ca67dbe3286452f23"), "weights.weight": 12},
[
{$set: {
newItem: {$reduce: {
input: {$getField: {
input: {$first: {
$filter: {
input: "$weights",
as: "item",
cond: {$eq: ["$$item.weight", 12]}
}
}},
field: "spotsAvailable"
}},
initialValue: [],
in: {$concatArrays: [
"$$value",
{$cond: [
{$and: [
{$eq: ["$$this.userId", "empty"]},
{$not: {$in: [ObjectId("636c1778f1d09191074f9690"), "$$value.userId"]}}
]},
[{
name: "Wayne Wrestler",
userId: ObjectId("636c1778f1d09191074f9690")
}],
["$$this"]
]}
]}
}}
}},
{$set: {
weights: {$map: {
input: "$weights",
in: {$cond: [
{$eq: ["$$this.weight", 12]},
{$mergeObjects: [
"$$this",
{spotsAvailable: "$newItem"}
]},
"$$this"
]}
}},
newItem: "$$REMOVE"
}}
])
See how it works on the playground example
You can first $unwind the weights for easier processing first. Use $reduce to iterate through the weights.spotsAvailable array and use a compound object to store the result and a flag to indicate whether it is updated or not. Finally use the result to $merge back to the original document.
db.collection.aggregate([
{
$match: {
"_id": ObjectId("6398c34ca67dbe3286452f23"),
createdBy: ObjectId("636c1778f1d09191074f9690"),
"weights.weight": 12,
"weights.spotsAvailable.userId": "empty"
}
},
{
"$unwind": "$weights"
},
{
"$addFields": {
"results": {
"$reduce": {
"input": "$weights.spotsAvailable",
"initialValue": {
result: [],
updated: false
},
"in": {
"$cond": {
"if": {
$and: [
{
$eq: [
false,
"$$value.updated"
]
},
{
$eq: [
"empty",
"$$this.userId"
]
}
]
},
"then": {
result: {
"$concatArrays": [
"$$value.result",
[
{
"name": "Wayne Wrestler",
"userId": ObjectId("636c1778f1d09191074f9690")
}
]
]
},
updated: true
},
"else": {
result: {
"$concatArrays": [
"$$value.result",
[
"$$this"
]
]
},
updated: "$$value.updated"
}
}
}
}
}
}
},
{
$set: {
"weights.spotsAvailable": "$results.result",
"results": "$$REMOVE"
}
},
{
$group: {
_id: "$_id",
"name": {
$first: "$name"
},
"createdBy": {
$first: "$createdBy"
},
"description": {
$first: "$description"
},
"date": {
$first: "$date"
},
"location": {
$first: "$location"
},
"weights": {
$push: "$weights"
},
"eventApplicants": {
$first: "$eventApplicants"
}
}
},
{
"$merge": {
"into": "collection",
"on": "_id"
}
}
])
Mongo Playground

MongoDB $lookup don't replace all of the other objects

I am trying to use the $lookup method to find users for this object. But when I use it, it replaces the other objects. The data that was outputed is this
"notifications": {
"author": [
{
"username": "UnusualAbsurd",
"status": "Michael Ohare",
"createdAt": "2022-03-08T14:02:53.728Z",
"id": "1",
"avatar": "https://avatars.dicebear.com/api/avataaars/UnusualAbsurd.png"
}
]
}
But what I expected was this
"notifications": [
"author": [
{
"username": "UnusualAbsurd",
"status": "Michael Ohare",
"createdAt": "2022-03-08T14:02:53.728Z",
"id": "1",
"avatar": "https://avatars.dicebear.com/api/avataaars/UnusualAbsurd.png"
}
],
"type": "REQUEST",
"value": "1"
]
How do I make it output the expected version?
This is my code right now
const data = await this.notificatioModel.aggregate([
{
$match: { author: id },
},
{
$project: { _id: 0, __v: 0 },
},
{
$lookup: {
from: 'users',
localField: 'notifications.author',
foreignField: 'id',
as: 'notifications.author',
pipeline: [
{
$project: { _id: 0, email: 0, password: 0 },
},
],
},
},
]);
This is my notification document
This is my user document

how to update embed document in mongoDB with mongoose

i have course model like
const courseSchema = new mongoose.Schema({
name:{
type: String,
required:[true,'course must have a name.'],
unique:true
},
duration :Number,
description :String,
imageCover :String,
images:Array,
price :Number,
curriculum:
[
{
week:Number,
description:String,
total:Number,
completed:Number,
progress:Number,
links:
[
{
name:String,
link:String,
img:String,
watched:{
type:Boolean,
default:false
}
}
]
}
],
tutors:[
{
type: mongoose.Schema.ObjectId,
ref:'user'
}
]
},
{
toJSON:{virtuals : true},
toObject:{virtuals : true}
});
i want to add new objects to links array in curriculum .client side will patch request with week object id , name and link ,inside update handler i am doing somthing like this.
const cour = await Course.findOneAndUpdate({"caricullum._id":req.params.w},
{$push:{name:req.body.name,link:req.body.link}},{
new : true,
});
w params contain curriculum week _id
{
"_id": {
"$oid": "6138abc106b3ad1d3477b3e2"
},
"images": [],
"tutors": [],
"name": "c/c++",
"duration": 8,
"price": 1299,
"imageCover": "cool_lion.jpg",
"description": "",
"curriculum": [
{
"_id": {
"$oid": "6138abc106b3ad1d3477b3e3"
},
"week": 1,
"description": "introduction to microcontroller and microprocesor",
"links": [
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3e4"
},
"name": "introduction",
"link": "https://www.youtube.com/embed/d0e6ScoS3Sw"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3e5"
},
"name": "difference between mc and mp",
"link": "https://www.youtube.com/embed/dcNk0urQsQM"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3e6"
},
"name": "building with microcontroller vs boards(arduino uno)",
"link": "https://www.youtube.com/embed/IdEcm3GU7TM"
}
]
},
{
"_id": {
"$oid": "6138abc106b3ad1d3477b3e7"
},
"week": 2,
"description": "introduction to arduino uno",
"links": [
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3e8"
},
"name": "introduction to arduino uno",
"link": "https://www.youtube.com/embed/BiCSW6QR6HA"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3e9"
},
"name": "IO PINS",
"link": "https://www.youtube.com/embed/OZGMLOwHYf8"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3ea"
},
"name": "setting up arduno uno for programming",
"link": "https://www.youtube.com/embed/ELUF8m24sZo"
}
]
},
{
"_id": {
"$oid": "6138abc106b3ad1d3477b3eb"
},
"week": 3,
"description": "interfacing with different sensors",
"links": [
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3ec"
},
"name": "LED Blinking(OUTPUT)",
"link": "https://www.youtube.com/embed/dnPPoetX0uw"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3ed"
},
"name": "interfacing with button(INPUT)",
"link": "https://www.youtube.com/embed/58Ynhqmvzoc"
},
{
"watched": false,
"_id": {
"$oid": "6138abc106b3ad1d3477b3ee"
},
"name": "16x2 LCD",
"link": "https://www.youtube.com/embed/Mr9FQKcrGpA"
}
]
}
],
"__v": 0
}
how to query for correct week document with req.params.w and push new document into links array
use arrayFilters
db.collection.update({},
{
$push: {
"curriculum.$[elem].links": {
link: "a",
name: "b",
whatched: "c"
}
}
},
{ new:true,
arrayFilters: [
{
"elem.week": 1
}
]
})
https://mongoplayground.net/p/nLV9UzbJlsc

Mongoose Aggregate Query For Getting Data From 4 Collection By Id and Group By Action

I have 3 collections
const userSchema = new mongoose.Schema ({
username : {
type : String,
trim: true
},
name : {
type : String,
trim: true
},
avatar : {
type : String
}
last_seen: {
type: Date,
default: Date.now
},
status: {
type : Boolean,
default: true
}
})
const hsVideoSchema = new mongoose.Schema ({
name : {
type : String,
trim: true,
required : true
},
url : {
type : String,
trim: true,
required : true
},
uploadedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
status: {
type : Boolean,
default: true
}
})
const fsVideoSchema = new mongoose.Schema ({
name : {
type : String,
trim: true,
required : true
},
url : {
type : String,
trim: true,
required : true
},
uploadedBy: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
status: {
type : Boolean,
default: true
}
})
Now, to keep user's action history, i created History Model as below :
const historySchema = new mongoose.Schema ({
user_id : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
hs_videoId : {
type: mongoose.Schema.Types.ObjectId,
ref: 'HsVideo',
default: null
},
fs_videoId : {
type: mongoose.Schema.Types.ObjectId,
ref: 'FsVideo',
default: null
},
action : {
type : String,
trim: true,
enum:['downloaded','viewed','liked','reported']
}
})
So, i will add new record in history collection when user will perform any action. At a time, out of 2 fields (hs_videId & fs_videoId) one field will be null and another will have id of ref document. In history collection, there can be same hs_videId/fs_videId with different action ('downloaded','viewed','liked','reported').
I am looking for query to get user's history by passing user_id and get all video history array with 2 sub arrays : HsVideos and FsVideos. Both sub array should have action's sub-array, which will have complete details of video (name, url,uploadedBy(UserArray),status).
What query i should write to get desire result ?
Query i tried already :
User.aggregate([
{ $match: {_id : ObjectId('5f3a90110132e115db700201')} },
{
$lookup: {
from: "histories",
as: "history",
pipeline: [
{
$match: {
user_id : ObjectId('5f3a90110132e115db700201')
}
}
]
},
},
]).exec(function(err, results){
if(err) console.log(err);
return res.status(200).json(results);
})
Please help ! Any help will be appreciated. Thanks.
EDIT : 1
I am expecting below result :
[
{
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "John",
"status": true,
"username": "jony"
"FsVideos": [
{
Viewed :[
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
},
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
}
],
Downloaded :[
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
},
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
}
],
Liked :[
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
},
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
}
],
Reported :[
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
},
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
}
],
}
],
"HsVideos": [
{
Viewed :[
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
},
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
}
],
Downloaded :[
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
},
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
}
],
Liked :[
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
},
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
}
],
Reported :[
{
"_id": ObjectId("5a934e000102030405000001"),
"url": "http://example.com/video.mp4",
"uploadedBy": {
"_id": ObjectId("5f3a90110132e115db700201"),
"avatar": "default.png",
"last_seen": ISODate("1970-01-01T00:00:00Z"),
"name": "A",
"status": true,
"username": "A"
},
}
],
}
]
}
]
This is totally a bad structure of schema, you really need to update it, because this will cause memory usage and execution time of the query,
You need to use lookup with pipeline and nested lookup,
$match your conditions for user
$lookup with histories collection and result will be in HsVideos
$match get histories of user_id
$lookup for hsVideo collection and result will be in hs_videoId
$match get hsVideo details
$lookup with user collection for updatedBy and result will be in updatedBy
$unwind deconstruct result updatedBy and it will be object
$unwind deconstruct hs_videoId because its array and we need object
$group by action and push required fields in v array
$project to show and hide required fields
User.aggregate([
{ $match: { _id: ObjectId("5f3a90110132e115db700201") } },
{
$lookup: {
from: "histories",
let: { user_id: "$_id" },
as: "HsVideos",
pipeline: [
{ $match: { $expr: { $eq: ["$user_id", "$$user_id"] } } },
{
$lookup: {
from: "hsVideo",
let: { hs_videoId: "$hs_videoId" },
as: "hs_videoId",
pipeline: [
{ $match: { $expr: { $eq: ["$$hs_videoId", "$_id"] } } },
{
$lookup: {
from: "user",
localField: "uploadedBy",
foreignField: "_id",
as: "uploadedBy"
}
},
{ $unwind: "$uploadedBy" }
]
}
},
{ $unwind: "$hs_videoId" },
{
$group: {
_id: "$action",
v: {
$push: {
_id: "$_id",
url: "$hs_videoId.url",
name: "$hs_videoId.name",
uploadedBy: "$hs_videoId.uploadedBy"
}
}
}
},
{ $project: { _id: 0, k: "$_id", v: 1 } }
]
}
},
i am repeating the above lines of explanation, repeat the same flow of HsVideos in FsVideos
{
$lookup: {
from: "histories",
let: { user_id: "$_id" },
as: "FsVideos",
pipeline: [
{ $match: { $expr: { $eq: ["$user_id", "$$user_id"] } } },
{
$lookup: {
from: "fsVideo",
let: { fs_videoId: "$fs_videoId" },
as: "fs_videoId",
pipeline: [
{ $match: { $expr: { $eq: ["$$fs_videoId", "$_id"] } } },
{
$lookup: {
from: "user",
localField: "uploadedBy",
foreignField: "_id",
as: "uploadedBy"
}
},
{ $unwind: "$uploadedBy" }
]
}
},
{ $unwind: "$fs_videoId" },
{
$group: {
_id: "$action",
v: {
$push: {
_id: "$_id",
url: "$fs_videoId.url",
name: "$fs_videoId.name",
uploadedBy: "$fs_videoId.uploadedBy"
}
}
}
},
{ $project: { _id: 0, k: "$_id", v: 1 } }
]
}
},
$addFields to convert FsVideos and HsVideos array to object, action as key and vlaue
{
$addFields: {
FsVideos: { $arrayToObject: "$FsVideos" },
HsVideos: { $arrayToObject: "$HsVideos" }
}
}
])
.exec(function(err, results){
if(err) console.log(err);
return res.status(200).json(results);
})
Playground

Mongodb node.js query on Embedded document Single field having multiple values.

Can anyone suggest me how can I get only those records from my collection? which is having multiple matched Values in my embedded document. here is my collection having name users.
{
"_id": "5b86fd75d595a923452366d7",
"name": "Mike I",
"email": "ppp#ppp.com",
"status": true,
"role": "seller",
"parking_space": [
{
"_id": "5b8cc33846e5360e741cae77",
"parking_name": "New Parking",
"street_address": "700 broadway",
"opening_days_and_timings": [
{
"day": "Monday",
"opening_time": "09:00",
"closing_time": "10:00",
"_id": "5b9119c93f7bc41306745a57"
},
{
"day": "Sunday",
"opening_time": "22:30",
"closing_time": "23:30",
"_id": "5b9119c93f7bc41306745a58"
},
{
"day": "Tuesday",
"opening_time": "11:00",
"closing_time": "23:59",
"_id": "5b9119c93f7bc41306745a59"
}],
"location":
{
"type": "Point",
"coordinates": [-117.15833099999998, 32.7157529]
},
"status": true,
},
{
"_id": "5b8e1df246e5360e741cae8a",
"parking_name": "Gupta's parking",
"street_address": "IT Park Rd, Phase - I",
"opening_days_and_timings": [
{
"day": "Wednesday",
"opening_time": "00:00",
"closing_time": "23:59",
"_id": "5b9119df3f7bc41306745a60"
},
{
"day": "Thursday",
"opening_time": "00:00",
"closing_time": "23:59",
"_id": "5b9119df3f7bc41306745a61"
}],
"location":
{
"type": "Point",
"coordinates": [76.84613349999995, 30.7259198]
},
"status": true,
}}
What I am trying to do here is to get only those parking data which is having days like "Wednesday" and "Thursday" only i just want that parking data. like this.
{
"_id": "5b86fd75d595a923452366d7",
"name": "Mike I",
"email": "ppp#ppp.com",
"status": true,
"role": "seller",
"parking_space": [
{
"_id": "5b8e1df246e5360e741cae8a",
"parking_name": "Gupta's parking",
"street_address": "IT Park Rd, Phase - I",
"opening_days_and_timings": [
{
"day": "Wednesday",
"opening_time": "00:00",
"closing_time": "23:59",
"_id": "5b9119df3f7bc41306745a60"
},
{
"day": "Thursday",
"opening_time": "00:00",
"closing_time": "23:59",
"_id": "5b9119df3f7bc41306745a61"
}],
"location":
{
"type": "Point",
"coordinates": [76.84613349999995, 30.7259198]
},
"status": true,
}}
and to get result like this i am using query as follow but it is not returning me the as i want. below is the query i am using.
User.aggregate([{
"$match": {
"parking_space.location": {
"$geoWithin": {
"$centerSphere": [
[parseFloat(req.body.long), parseFloat(req.body.lat)], 7 / 3963.2
]
}
},
$and : [ { "parking_space.opening_days_and_timings.day" : 'Thursday' }, { "parking_space.opening_days_and_timings.day" : 'Wednesday' }
"parking_space.opening_days_and_timings.day": getDayOfWeek(req.body.date)
}
}, {
"$unwind": "$parking_space"
}, {
"$match": {
"parking_space.location": {
"$geoWithin": {
"$centerSphere": [
[parseFloat(req.body.long), parseFloat(req.body.lat)], 7 / 3963.2
]
}
},
}
}], function(err, park_places) {
if (err) {
return res.send({
data: err,
status: false
});
} else {
return res.send({
data: park_places,
status: true,
msg: "Parking data according to location"
});
}
});
This is the query i am using which is not returning the above desired result can someone suggest me something to get the result
You can use below aggregation.
User.aggregate([
{
"$match": {
"parking_space.location": {
"$geoWithin": {
"$centerSphere": [
[parseFloat(req.body.long), parseFloat(req.body.lat)], 7 / 3963.2
]
}
},
{"parking_space.opening_days_and_timings.day" :{"$in":['Thursday', 'Wednesday', getDayOfWeek(req.body.date)]}}
}
},{
"$addFields": {
"parking_space": {
"$filter": {
"input": "$parking_space",
"cond": {"$setIsSubset":[['Thursday', 'Wednesday', getDayOfWeek(req.body.date)], "$$this.opening_days_and_timings.day"]}
}
}
}
}
],
function(err, park_places) {
if (err) {
return res.send({
data: err,
status: false
});
} else {
return res.send({
data: park_places,
status: true,
msg: "Parking data according to location"
});
}
});

Resources