how to update embed document in mongoDB with mongoose - node.js

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

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

How to use aggregation with nested document?

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",
},
},
];
};

Retrieve value from mongoose object after query

I have a query as follows :
await Categories.findOne({slug : _gender} , { _id : 0 , categories :{$elemMatch : {slug : _mainCategory}}})
and the model is this :
const categoriesSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: { type: String },
slug: { type: String }, ==> match first param with this
categories: [
{
_id: mongoose.Schema.Types.ObjectId,
title: { type: String },
slug: { type: String }, ==> match the second param with this
categories: [ ==> retrieve this field
{
_id: mongoose.Schema.Types.ObjectId,
title: { type: String },
slug: { type: String },
},
],
},
],
});
_gender and _mainCategory are params.
The output it gives is as follows:
{
"categories": [
{
"id": "12",
"title": "Ayakkabı",
"slug": "kadin-ayakkabi", // ==> this is the { _id : 0 , categories :{$elemMatch : {slug : _mainCategory}} part, one level above this is the part which matches the {slug : _gender}
"image": "https://webizade.com/bm/img/",
"categories": [ // ===> this is the value I want to retrieve after the query
{
"id": "100",
"title": "Topuklu Ayakkabı",
"filter_title": "ayakkabi",
"slug": "kadin-topuklu-ayakkabi-x-g1-c107",
"image": "https://webizade.com/bm/img/"
},
{
"id": "101",
"title": "Spor Ayakkabı",
"filter_title": "ayakkabi",
"slug": "spor-ayakkabi",
"image": "https://webizade.com/bm/img/"
},
{
"id": "102",
"title": "Günlük Ayakkabı",
"filter_title": "ayakkabi",
"slug": "kadin-gunluk-ayakkabi-x-g1-c1352",
"image": "https://webizade.com/bm/img/"
},
{
"id": "103",
"title": "Babet",
"filter_title": "ayakkabi",
"slug": "kadin-babet-x-g1-c113",
"image": "https://webizade.com/bm/img/"
},
{
"id": "104",
"title": "Sandalet",
"filter_title": "ayakkabi",
"slug": "kadin-sandalet-x-g1-c111",
"image": "https://webizade.com/bm/img/"
},
{
"id": "105",
"title": "Terlik",
"filter_title": "ayakkabi",
"slug": "kadin-terlik-x-g1-c110",
"image": "https://webizade.com/bm/img/"
},
{
"id": "144",
"title": "Kar Botu",
"filter_title": "ayakkabi",
"slug": "kar-botu",
"image": "https://webizade.com/bm/img/"
}
]
}
]
}
As far as matching the correct object goes, this is correct. However, I want to retrieve the "categories" array inside the outer categories array after finding the correct object. But I don't know the correct syntax for doing that.
Appreciate any help.

Populate data from another collection mongoose

I have 3 collections users, profiles and trustedcontacts. Profiles and trustedcontacts have ref to users
My db collections
I have collection users
{
"_id": {
"$oid": "5c5ecaf6134fc342d4b1a9d5"
},
"name": "User",
"email": "user#gmail.com",
"password": "$2a$10$BXxwpMTFK1a0aWclaqJYve4f3SZyi/emwHKv5rY2GNzrPSEsIJhzi",
},
{
"_id": {
"$oid": "5c64968cae53a8202c963223"
},
"name": "User1",
"email": "user1#gmail.com",
"password": "$2a$10$BXxwpMTFK1a0aWclaqJYve4f3SZyi/emwHKv5rY2GNzrPSEsIJhzi",
},
{
"_id": {
"$oid": "5c69968cae53a8202c963554"
},
"name": "User1",
"email": "user1#gmail.com",
"password": "$2a$10$BXxwpMTFK1a0aWclaqJYve4f3SZyi/emwHKv5rY2GNzrPSEsIJhzi",
}
collection profiles
{
"_id": {
"$oid": "5c5ecb17134fc342d4b1a9d6"
},
"user": {
"$oid": "5c5ecaf6134fc342d4b1a9d5"
},
"handle": "handle",
"company": "test"
},
{
"_id": {
"$oid": "5c6496ebae53a8202c963224"
},
"user": {
"$oid": "5c64968cae53a8202c963223"
},
"handle": "handle1",
"company": ""
},
{
"_id": {
"$oid": "5c6496ebae53a8202c963224"
},
"user": {
"$oid": "5c69968cae53a8202c963554"
},
"handle": "handle2",
"company": ""
}
collection trustedcontacts
{
"_id": {
"$oid": "5d76008e4b98e63e58cb34cc"
},
"approvedTrustedContacts": [
{
"_id": {
"$oid": "5d764e411b7476462cf6b540"
},
"user": {
"$oid": "5c5ecaf6134fc342d4b1a9d5"
}
},
{
"_id": {
"$oid": "5d764e411b7476462cf6b541"
},
"user": {
"$oid": "5c64968cae53a8202c963223"
}
}
],
"pendingApprovalContacts": [],
"waitingForApprovalContacts": [],
"user": {
"$oid": "5d76008e4b98e63e58cb34cb"
}
}
//My Schemas
const UserSchema = new mongoose.Schema({
name: {
type: String,
},
email: {
type: String,
}
});
export default mongoose.model('User', UserSchema);
const ProfileSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
handle: {
type: String,
},
company: {
type: String,
},
});
export default mongoose.model('Profile', ProfileSchema);
import mongoose from 'mongoose';
const TrustedContactsSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
approvedTrustedContacts: [
{
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}
],
...
});
export default mongoose.model('TrustedContacts', TrustedContactsSchema);
I can populate trusted contact by user
const user = await TrustedContacts.findOne({ user: req.user.id }).populate('approvedTrustedContacts.user', ['name', 'email']);
and I got
"user": {
"date": "2019-09-09T07:32:20.174Z",
"_id": "5d76008e4b98e63e58cb34cc",
"approvedTrustedContacts": [
{
"_id": "5d764e411b7476462cf6b540",
"user": {
"_id": "5c5ecaf6134fc342d4b1a9d5",
"name": "User",
"email": "user#gmail.com",
}
},
{
"_id": "5d764e411b7476462cf6b541",
"user": {
"_id": "5c64968cae53a8202c963223",
"name": "User1",
"email": "user1#gmail.com",
}
}
],
"pendingApprovalContacts": [],
"waitingForApprovalContacts": [],
"user": "5d76008e4b98e63e58cb34cb",
}
Expected Output
It is possible to get list of approvedTrustedContacts with profile data
"approvedTrustedContacts": [
{
"_id": "5d764e411b7476462cf6b540",
"user": {
"_id": "5c5ecaf6134fc342d4b1a9d5",
"name": "User",
"email": "user#gmail.com",
},
"handle": "handle",
"company": "test"
},
{
"_id": "5d764e411b7476462cf6b541",
"user": {
"_id": "5c64968cae53a8202c963223",
"name": "User1",
"email": "user1#gmail.com",
},
"handle": "handle1",
"company": "test1"
}
],
Also I have joined 2 collections like this
let result1 = await TrustedContacts.aggregate([
{ $lookup: { from: "profiles", localField: "user", foreignField: "user", as: "approvedTrustedContacts" } },
]);
And I got
{
"_id": "5d76008e4b98e63e58cb34cc",
"approvedTrustedContacts": [
{
"_id": "5d764f551b7476462cf6b542",
"user": "5d76008e4b98e63e58cb34cb",
"handle": "handle",
"company": "test",
},
{
"_id": "5c5ecb17134fc342d4b1a9d6",
"user": "5c5ecaf6134fc342d4b1a9d5",
"handle": "handle1",
"company": "test1",
}
],
"pendingApprovalContacts": [],
"waitingForApprovalContacts": [],
"user": "5d76008e4b98e63e58cb34cb",
}
],
Now I don't know how to polute user to have an output like this:
{
"_id": "5d76008e4b98e63e58cb34cc",
"approvedTrustedContacts": [
{
"_id": "5d764f551b7476462cf6b542",
"user": {
"_id": "5c5ecaf6134fc342d4b1a9d5",
"name": "User",
"email": "user#gmail.com",
},
"handle": "handle"
"company": "test",
},
{
"_id": "5c5ecb17134fc342d4b1a9d6",
"user": {
"_id": "5c64968cae53a8202c963223",
"name": "User1",
"email": "user1#gmail.com",
},
"handle": "handle1",
"company": "test1",
}
],
"pendingApprovalContacts": [],
"waitingForApprovalContacts": [],
"user": "5d76008e4b98e63e58cb34cb",
}
],
My solution
let result = await TrustedContacts.aggregate([
{ $lookup: { from: "profiles", localField: "approvedTrustedContacts.user", foreignField: "user", as: "approvedTrustedContacts.profile" } },
{ $unwind: "$approvedTrustedContacts.profile" },
{ $lookup: { from: "users", localField: "approvedTrustedContacts.profile.user", foreignField: "_id", as: "approvedTrustedContacts.profile.user" } },
{ $unwind: "$approvedTrustedContacts.profile.user" },
{ $group :{
_id: "$_id",
"date": {"$first": "$date"},
"approvedTrustedContacts": {"$push": "$approvedTrustedContacts"},
}}
]);
As an output I have
{
"_id": "5d76008e4b98e63e58cb34cc",
"date": "2019-09-09T07:32:20.174Z",
"approvedTrustedContacts": [
{
"profile": {
"_id": "5c5ecb17134fc342d4b1a9d6",
"skills": [
"test"
],
"date": "2019-02-09T12:42:48.969Z",
"user": {
"_id": "5c5ecaf6134fc342d4b1a9d5",
"data": "2019-02-09T12:42:48.716Z",
"name": "User",
"email": "user#gmail.com",
},
"handle": "handle",
"company": "test",
}
},
{
"profile": {
"_id": "5c6496ebae53a8202c963224",
"skills": [
"qwqwqwqwqw"
],
"date": "2019-02-13T22:11:04.119Z",
"user": {
"_id": "5c64968cae53a8202c963223",
"data": "2019-02-13T22:11:03.807Z",
"name": "User1",
"email": "user1#gmail.com",
},
"handle": "handle1",
"company": "test1",
}
}
]
}
```

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