{
"success": true,
"message": "Result",
"data": [
{
"Here": [
{
"_id": "5ee97ee7f25d1c1482717bdf",
"email": "test1#test.io",
"profileImages": [],
"username": "test1",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location",
"firstName": "test1",
"lastName": "test1",
}
]
},
{
"Here": [
{
"_id": "5ee97ef2f25d1c1482717be1",
"email": "test2#test.io",
"profileImages": [],
"username": "test2",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location"
}
]
}
],
}
What I am expecting is this
{
"success": true,
"message": "Result",
data: [
{
"_id": "5ee97ee7f25d1c1482717bdf",
"email": "test1#test.io",
"profileImages": [],
"username": "test1",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location",
"firstName": "test1",
"lastName": "test1"},
{
"_id": "5ee97ef2f25d1c1482717be1",
"email": "test2#test.io",
"profileImages": [],
"username": "test2",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location"
}
]
}
Query I am using is for this response is below using aggregation in mongodb, lookup and project which is leading me to the some undesired response
db.collections.aggregate( [
{
$lookup: {
from: 'users',
as: 'Here',
let: {
whoDid: '$whoDid'
},
pipeline: [
{
"$match": { "$expr": { "$eq": ["$_id", "$$whoDid"] } }
},
{
$project: {
_id: 1,
email: 1,
profileImages: 1,
username: 1,
birthday: 1,
phoneNumber: 1,
firstName: 1,
lastName: 1,
fullName: 1,
// age: {$year: "$birthday"}
age: {
$divide: [{ $subtract: [new Date(), "$birthday"] },
(31558464000)]
}
}
}
],
}
},
{
$project:{
Here:1,
_id:0
}
} ,
])
who did table is one of the collection I have where I have stored the user Id and later I am populating the data using lookup
{
"_id" : ObjectId("5ee988eb1aac0022e15dbb7b"),
"whoDid" : ObjectId("5ee97ef2f25d1c1482717be1"),
"toWhomDid" : ObjectId("5ee97ec0f25d1c1482717bdd"),
"modified_at" : ISODate("2020-06-17T03:07:23.217Z"),
"created_at" : ISODate("2020-06-17T03:07:23.217Z"),
"__v" : 0
}
{
"_id" : ObjectId("5ee988eb1aac0022e15dbb7c"),
"whoDid" : ObjectId("5ee97ec0f25d1c1482717bdd"),
"toWhomDid" : ObjectId("5ee97ef2f25d1c1482717be1"),
"modified_at" : ISODate("2020-06-17T03:07:23.220Z"),
"created_at" : ISODate("2020-06-17T03:07:23.220Z"),
"__v" : 0
}
Can anyone suggest me any better option so that I can get a desired respose?
It is possible to use reduce method:
obj.data = obj.data.reduce((a, c) => {
a.push(...c.Here);
return a;
}, [])
An example:
let obj = {
"success": true,
"message": "Result",
"data": [ {
"Here": [ {
"_id": "5ee97ee7f25d1c1482717bdf", "email": "test1#test.io",
"profileImages": [], "username": "test1",
"birthday": "2020-06-11T10:11:32.000Z", "phoneNumber": "+910000000000", "location": "Test Location",
"firstName": "test1", "lastName": "test1",
}
]
},
{
"Here": [ {
"_id": "5ee97ef2f25d1c1482717be1",
"email": "test2#test.io",
"profileImages": [],
"username": "test2",
"birthday": "2020-06-11T10:11:32.000Z",
"phoneNumber": "+910000000000",
"location": "Test Location"
}
]
}
]
};
obj.data = obj.data.reduce((a, c) => {
a.push(...c.Here);
return a;
}, [])
console.log(obj);
Add these extra steps into your aggregation pipeline:
{
$unwind: "$Here"
},
{
$replaceWith: "$Here"
}
MongoPlayground
Note: You can replace $project: { _id: 1, email: 1, ... to this:
{
$addFields:{
age: {
$divide: [{ $subtract: [new Date(), "$birthday"] },(31558464000)]
}
}
}
Related
I'm new as MongoDB, I have 2 collections: User and Video with below structure. When user like a video, video's _id will be added to liked_videos on user collection. liked_videos is an array of _id
video collection
{
_id
mp4_url,
liked_count
}
User collection
{
_id,
username,
password,
liked_videos: [ // videos _id array ]
}
How do I query to get the user's liked videos? Like below?
[
{
_id: 1
mp4_url,
liked_count
},
{
_id: 2
mp4_url,
liked_count
},
...
]
Thank you
You need to use $lookup to join collections and $size to get the array size
db.video.aggregate([
{
"$lookup": {
"from": "user",
"localField": "_id",
"foreignField": "liked_videos",
"as": "join_video"
}
},
{
"$project": {
liked_count: {
$size: "$join_video"
}
}
}
])
Working Mongo playground
Try this way
db={
"video": [
{
"_id": 1,
"mp4_url": "url1",
"liked_count": 2,
"quantity": 2
},
{
"_id": 2,
"mp4_url": "url2",
"liked_count": 3,
"quantity": 1
},
{
"_id": 3,
"mp4_url": "url2",
"liked_count": 3,
"quantity": 4
}
],
"User": [
{
"_id": 1,
"username": "almonds",
"password": "pwd",
"Likedvideos": [
"aaa",
"ffff"
]
},
{
"_id": 2,
"username": "almonds",
"password": "pwd",
"Likedvideos": [
"qqq",
"bbbb"
]
},
{
"_id": 3,
"username": "almonds",
"password": "pwd",
"Likedvideos": [
"ccc",
"ffff"
]
},
{
"_id": 4,
"username": "almonds",
"password": "pwd",
"Likedvideos": [
"bbbb",
"ffff"
]
},
{
"_id": 5,
"username": "almonds",
"password": "pwd",
"Likedvideos": [
"qqq",
"ffff"
]
},
{
"_id": 6
}
]
}
Query :
db.video.aggregate([
{
$match: {
_id: 1
}
},
{
"$lookup": {
"from": "User",
"localField": "_id",
"foreignField": "_id",
"as": "data"
},
},
{
$unwind: "$data"
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$data",
"$$ROOT"
]
}
}
},
{
$project: {
data: 0
}
}
])
Output:
[
{
"Likedvideos": [
"aaa",
"ffff"
],
"_id": 1,
"liked_count": 2,
"mp4_url": "url1",
"password": "pwd",
"quantity": 2,
"username": "almonds"
}
]
mongoplayground
i want to filter the result as the following in mongodb. I use $lookup to populate the result from another collection. Please check my following code
This code below is what i get
{
"_id": "5f3d563122de0730d0f6a754",
"barcode": "1234",
"productname": "Lays Packet",
"brandName": "Lays",
"productSize": "12",
"price": "12",
"quant": "12",
"imageurl": "http://localhost:3000/images/imageurl-1597855281050.jpg",
"remaining": "12",
"creator": "3d943b957fb5db510d824c5cbd6e8f7d",
"__v": 0,
"source": [
{
"_id": "5f3a9bbc325a074240a1a815",
"firstname": "test",
"lastname": "test",
"storename": "test",
"gst": "test",
"phoneNumber": 1,
"email": "1#demo.com",
"address1": "test",
"address2": "test",
"city": "test",
"state": "test",
"country": "test",
"zip": "1",
"password": "1",
"usertype": 3,
"unique_SHOP": "3d943b957fb5db510d824c5cbd6e8f7d",
"__v": 0
}
]
},
How to retrieve only unique_SHOP and zip from source listing.I want result like the one below with one or more fields
{
"_id": "5f3d563122de0730d0f6a754",
"barcode": "1234",
"productname": "Lays Packet",
"brandName": "Lays",
"productSize": "12",
"price": "12",
"quant": "12",
"imageurl": "http://localhost:3000/images/imageurl-1597855281050.jpg",
"remaining": "12",
"creator": "3d943b957fb5db510d824c5cbd6e8f7d",
"__v": 0,
"source": [
{
"zip": "1",
"unique_SHOP": "3d943b957fb5db510d824c5cbd6e8f7d",
}
]
},
The query i use
List.aggregate([
{$match:
{ productname: { $regex: req.params.query,$options: "i" }}
},
{ $lookup:{
from: "suppliers",
localField: "creator",
foreignField: "unique_SHOP",
as: "source"
}
},
])
You can try $lookup with pipeline,
$match condition of creator id
$project to display required fields
{
$lookup: {
from: "suppliers",
as: "source",
let: { creator: "$creator" },
pipeline: [
{
$match: {
$expr: { $eq: ["$$creator", "$_id"] }
}
},
{
$project: {
_id: 0,
zip: 1,
unique_SHOP: 1
}
}
]
}
}
Playground
how to make this data to asc order by user's first name and user's last name.
I got the response, want to sort the records by user's first name but it is taking from creation date I guess when using sort how can I make it base on user's first name and user's last name please guide
{
"response": {
"items": [
{
"_id": "5e71f86bd300b313df52fb2f",
"last_message": {
"text": "Alex",
"users": [
{
"_id": "5e4a8d2d3952132a08ae5764",
"first_name": "zack",
"last_name": "Write"
}
]
},
"texter": [
"alex",
"$0ctg"
],
"title": "New group1",
"group": true,
"members": [
{
"_id": "5e4a8afc3952132a08ae575e",
"first_name": "test3",
"last_name": "test4"
}
],
"managers": [
"5e4a8afc3952132a08ae575e"
],
"member": {
"_id": "5e4a8afc3952132a08ae575e",
"first_name": "test3",
"last_name": "test4"
}
},
{
"_id": "5e4e740f380054797d9db621",
"last_message": {
"text": "",
"users": [
{
"_id": "5e4a8d2d3952132a08ae5764",
"first_name": "yuhan",
"last_name": "jacob"
}
]
},
"texter": [
"",
"",
"",
"",
"",
"new iphone x\n brand new iphone wv wwvqzwzvq had sqswgscq wow you wholeheartedly q \n $600.00",
"helo",
"hello",
"hi"
],
"members": [
{
"_id": "5e4d0973babf2b74ca868f4d",
"first_name": "alex",
"last_name": "hales"
}
],
"managers": [],
"member": {
"_id": "5e4d0973babf2b74ca868f4d",
"first_name": "alex",
"last_name": "hales"
}
}
]
}
}
Tried
{
$sort: {
users: 1,
}
},
doesn't help much
Also if I would like to add two field asc desc order what would be the process in MongoDB
Try this hope this will help you !
{
$sort: { "users.first_name": 1 }
},
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",
}
}
]
}
```
I was stuck on mongodb aggregation to get count of rating. i have already trying to make myself pipeline. looks above
data (products collection)
{
"status": 200,
"message": null,
"data": {
"_id": "5cc570257631a313d489ba4a",
"media": [
"httpsdssd",
"dfdfd"
],
"comment": [
"5cc57f1053273c05cc60e707",
"5cc585bf6ff7a812e0e7d9d9",
"5cc5c654bc73b408787ffadc",
"5cc5c6e3bc73b408787ffadd"
],
"store": "5cc2c9710bc5d615781fcf8a",
"meta": {
"title": "Traveling Sumbar",
"price": "150000",
"max": 5,
"duration": 6,
"description": "fdf fdnf jdnf dfnkdknfkkd",
"location": {
"province": "Sumbar",
"city": "Padang"
}
},
"option": {
"is_promo": false,
"auto_delete": null
},
"created_at": "2019-04-28T09:19:33.233Z",
"updated_at": "2019-04-28T15:29:39.921Z",
"__v": 0
}
}
comment data on (products_comment)
{
"helped": [],
"deleted_at": null,
"_id": "5cc3276e32940613506c3848",
"user": "5cc2c7fb0bc5d615781fcf86",
"rating": "4",
"body": "fdfdlfdlfkdlfkdlfkd",
"created_at": "2019-04-26T15:44:46.224Z",
"updated_at": "2019-04-28T16:00:48.400Z",
"__v": 0
},
{
"helped": [],
"deleted_at": null,
"_id": "5cc3276e32940613506c3848",
"user": "5cc2c7fb0bc5d615781fcf86",
"rating": "4",
"body": "fdfdlfdlfkdlfkdlfkd",
"created_at": "2019-04-26T15:44:46.224Z",
"updated_at": "2019-04-28T16:00:48.400Z",
"__v": 0
},
{
"helped": [],
"deleted_at": null,
"_id": "5cc3276e32940613506c3848",
"user": "5cc2c7fb0bc5d615781fcf86",
"rating": "3",
"body": "fdfdlfdlfkdlfkdlfkd",
"created_at": "2019-04-26T15:44:46.224Z",
"updated_at": "2019-04-28T16:00:48.400Z",
"__v": 0
},
I have already try make aggregation pipeline like this
{
$lookup: {
from: "stores",
localField: "store",
foreignField: "_id",
as: "store"
}
},
{
$lookup: {
from: "products_comment",
localField: "comment",
foreignField: "_id",
as: "comment"
}
},
{ $unwind: "$comment" },
{
$project: {
media: 1,
"store.type": 1,
"store.profile.address.city": 1,
"meta.title": 1,
"meta.price": 1,
"comment.rating": 1
}
}
but result unlike expectation, i want result like this
{
"_id": "5cc570257631a313d489ba4a",
"media": [
"httpsdssd",
"dfdfd"
],
"comment": {
1_rating: 0, <value of rating: count of value>
2_rating: 3,
3_rating: 5,
....,
},
"store": [
{
"type": "craft",
"profile": {
"address": {
city: "Padang
}
}
}
],
"meta": {
"title": "Traveling Sumbar",
"price": "150000"
}
}
how i do to solve my problem ?
Below Query will give you exactly expected Output :
var query = [
{
$lookup: {
from: "comments",
localField: "comment",
foreignField: "_id",
as: "comments"
}
},
{ $unwind: "$comments" },
{ $group : {
_id: {
_id: '$_id',
rating: '$comments.rating',
media : '$media',
meta : '$meta',
store : '$store'
},
totalRating: {$sum: 1}
}
},
{
$group : {
_id : {
_id : '$_id._id',
media : '$_id.media',
meta : '$_id.meta',
store : '$_id.store'
},
comments : {
$push : {
rating : '$_id.rating',
totalRating : '$totalRating'
}
}
}
},
{
$lookup: {
from: "stores",
localField: "store",
foreignField: "_id",
as: "store"
}
},
{
$project: {
'_id' : '$_id._id',
media : '$_id.media',
store : '$store',
meta : {
title: '$_id.meta.title',
price : '$_id.meta.price'
},
comments : { "$arrayToObject": {
"$map": {
"input": "$comments",
"as": "el",
"in": {
"k": "$$el.rating",
"v": "$$el.totalRating"
}
}
}
}
}
}
];
Output :
{
"_id" : ObjectId("5cc718715290f4ed550f5305"),
"media" : [
"httpsdssd",
"dfdfd"
],
"store" : [ ],
"meta" : {
"title" : "Traveling Sumbar",
"price" : "150000"
},
"comments" : {
"3" : 1,
"4" : 2
}
}
{
"_id" : ObjectId("5cc88d99d486568c5745e4b7"),
"media" : [
"maha",
"sagar"
],
"store" : [ ],
"meta" : {
"title" : "Sagar Sumbar",
"price" : "15000"
},
"comments" : {
"3" : 2,
"5" : 1,
"1" : 1
}
}
NOTE: Store data will be fetched from stores collection by $lookup. I don't have a model/data so, not in the output.