MongoDB : lookup exact match without false rows - mongodb

I have 3 tables :
accounts:[
{id:111,name:'john'},
{id:222,name:'due'}
]
workoutTypes:[
{id:1,title:'a'},
{id:2,title:'b'}
]
accountrecords:[
{_id:10,workoutTypeId:1,accountId:111},
{_id:11,workoutTypeId:1,accountId:222}
]
I used this command to group all account records by workout type that match to the current account like that:
db.workoutTypes.aggregate([
{
$lookup: {
from: "accountrecords",
localField: "_id",
foreignField: "workoutTypeId",
as: "records"
}
},
{
$match: {
$and: [
{ "records": { $ne: [] } },
{ "records.accountId": { $eq: mongoose.Types.ObjectId(accountId) } },
]
}
},
])
the issue that I'm getting the records that related to both of accounts.
saw that eq command return a false value for non-match values.
there is an option to get only the record that matches to current account?

First of all your localField on workoutTypes collection must be id, not _id. Probably a typo from your side. Secondly, you need to use $redact operator if you want to restrict the content. $match actually works as expected, but it actually isn't checking whether all your sub documents are satisfying the criteria.
Update:
Try this query:
db.workoutTypes.aggregate([
{
$lookup: {
from: "accountrecords",
localField: "_id",
foreignField: "workoutTypeId",
as: "records"
}
},
{$match:{"records.accountId":{$exists:true}, "records.accountId":{$eq:ObjectId("5a604b18280420c03e8d3a23")}}},
{$redact:{
$cond:{
if:{$or:[{$eq:["$accountId",ObjectId("5a604b18280420c03e8d3a23")]},{$not:"$accountId"}]},
then:"$$DESCEND",
else:"$$PRUNE"
}
}}
])
And the output is:
/* 1 */
{
"_id" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"updatedAt" : ISODate("2018-04-07T11:59:52.583Z"),
"createdAt" : ISODate("2018-04-07T11:59:52.583Z"),
"title" : "Snatch",
"__v" : 0,
"records" : [
{
"_id" : ObjectId("5acb1b666b08493b30deed92"),
"updatedAt" : ISODate("2018-04-09T07:51:02.294Z"),
"createdAt" : ISODate("2018-04-09T07:51:02.294Z"),
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"repetition" : 4,
"weight" : 120,
"__v" : 0
},
{
"_id" : ObjectId("5acb1b6f6b08493b30deed93"),
"updatedAt" : ISODate("2018-04-09T07:51:11.878Z"),
"createdAt" : ISODate("2018-04-09T07:51:11.878Z"),
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"repetition" : 5,
"weight" : 130,
"__v" : 0
},
{
"_id" : ObjectId("5ace23aa1c4d590dc049e94e"),
"updatedAt" : ISODate("2018-04-11T15:03:06.824Z"),
"createdAt" : ISODate("2018-04-11T15:03:06.824Z"),
"repetition" : 124,
"weight" : 32,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"__v" : 0
},
{
"_id" : ObjectId("5ace23b21c4d590dc049e94f"),
"updatedAt" : ISODate("2018-04-11T15:03:14.293Z"),
"createdAt" : ISODate("2018-04-11T15:03:14.293Z"),
"repetition" : 325,
"weight" : 235,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"__v" : 0
},
{
"_id" : ObjectId("5acc8ef5345125417cca18e3"),
"updatedAt" : ISODate("2018-04-10T10:16:21.709Z"),
"createdAt" : ISODate("2018-04-10T10:16:21.709Z"),
"repetition" : 123,
"weight" : 456,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8b2b8fb45830ff77cd33b"),
"__v" : 0
}
]
}
/* 2 */
{
"_id" : ObjectId("5acdf56afd5ca008d01b706f"),
"updatedAt" : ISODate("2018-04-11T11:45:46.192Z"),
"createdAt" : ISODate("2018-04-11T11:45:46.192Z"),
"title" : "Jerk",
"__v" : 0,
"records" : [
{
"_id" : ObjectId("5acdf597fd5ca008d01b7070"),
"updatedAt" : ISODate("2018-04-11T11:46:31.674Z"),
"createdAt" : ISODate("2018-04-11T11:46:31.674Z"),
"repetition" : 12,
"weight" : 100,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5acdf56afd5ca008d01b706f"),
"__v" : 0
}
]
}
/* 3 */
{
"_id" : ObjectId("5ace336ed36c780e6ce76d5d"),
"updatedAt" : ISODate("2018-04-11T16:10:22.483Z"),
"createdAt" : ISODate("2018-04-11T16:10:22.483Z"),
"title" : "Weight lifting",
"__v" : 0,
"records" : [
{
"_id" : ObjectId("5ace337ed36c780e6ce76d5e"),
"updatedAt" : ISODate("2018-04-11T16:10:38.708Z"),
"createdAt" : ISODate("2018-04-11T16:10:38.708Z"),
"repetition" : 21,
"weight" : 100,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ace336ed36c780e6ce76d5d"),
"__v" : 0
}
]
}
/* 4 */
{
"_id" : ObjectId("5ac8cf5ef14469169d8627e8"),
"updatedAt" : ISODate("2018-04-07T14:02:06.155Z"),
"createdAt" : ISODate("2018-04-07T14:02:06.155Z"),
"title" : "Double under",
"__v" : 0,
"records" : [
{
"_id" : ObjectId("5acc8f11345125417cca18e4"),
"updatedAt" : ISODate("2018-04-10T10:16:49.069Z"),
"createdAt" : ISODate("2018-04-10T10:16:49.069Z"),
"repetition" : 111111,
"weight" : 222222,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8cf5ef14469169d8627e8"),
"__v" : 0
},
{
"_id" : ObjectId("5ace2d7b1c4d590dc049e950"),
"updatedAt" : ISODate("2018-04-11T15:44:59.722Z"),
"createdAt" : ISODate("2018-04-11T15:44:59.722Z"),
"weight" : 23,
"repetition" : 123555555,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8cf5ef14469169d8627e8"),
"__v" : 0
}
]
}
/* 5 */
{
"_id" : ObjectId("5ac8cfdd79a48216b3e048b0"),
"updatedAt" : ISODate("2018-04-07T14:04:13.670Z"),
"createdAt" : ISODate("2018-04-07T14:04:13.670Z"),
"title" : "Push-ups",
"__v" : 0,
"records" : [
{
"_id" : ObjectId("5accc1f1cd58a407c6562f79"),
"updatedAt" : ISODate("2018-04-10T13:53:53.933Z"),
"createdAt" : ISODate("2018-04-10T13:53:53.933Z"),
"repetition" : 123,
"weight" : 456000,
"accountId" : ObjectId("5a604b18280420c03e8d3a23"),
"workoutTypeId" : ObjectId("5ac8cfdd79a48216b3e048b0"),
"__v" : 0
}
]
}
Now you just replace ObjectId("5a604b18280420c03e8d3a23") in the query with your mongoose code mongoose.Types.ObjectId(accountId) and you should be good now.

Related

Filter day on MongoDB

I have a collection called "batches" that has the field "createdAt" with ISODate:
{
"_id" : ObjectId("5f6134ecf908840018f2e9ea"),
"status" : "BATCH_PROCESSING",
"groupId" : 13,
"type" : "not",
"finished" : false,
"scheduledTo" : "2020-09-15T18:50:51-03:00",
"identifier" : "COLABORADORES",
"createdAt" : "2020-09-18T18:41:00-03:00",
"__v" : 0
}
{
"_id" : ObjectId("5f6144d7863bb40018045906"),
"status" : "BATCH_PROCESSING",
"groupId" : 13,
"type" : "not",
"finished" : false,
"scheduledTo" : "2020-09-16T19:48:00-03:00",
"identifier" : "COLABORADORES",
"createdAt" : "2020-09-15T19:48:55-03:00",
"__v" : 0
}
{
"_id" : ObjectId("5f617021b985c1001974c3af"),
"status" : "CANCELED",
"groupId" : 13,
"type" : "not",
"finished" : true,
"scheduledTo" : "2020-09-15T23:06:00-03:00",
"identifier" : "COLABORADORES",
"createdAt" : "2020-09-18T22:53:37-03:00",
"__v" : 0,
"numberOfLines" : 1
}
I need to filter only documents in a specific date. I tried many ways but it didn't bring the documents :
db.getCollection("batches").find(
{ createdAt : {
"$gte": ISODate("2020-09-15T00:00:00Z"),
"$lt": ISODate("2020-09-19T00:00:00Z")
} }
);
db.getCollection("batches").find({ createdAt : Date("2020-09-15")}
);
The query works well, but the answer is always:
Fetched 0 record(s) in 136ms
How do I do this filter correctly?
Your data is malformed. Your field 'createdDate' is a string, not an ISODate(). Consider this...
db.batches.insertMany([
{
"_id" : ObjectId("5f6134ecf908840018f2e9ea"),
"status" : "BATCH_PROCESSING",
"groupId" : 13,
"type" : "not",
"finished" : false,
"scheduledTo" : "2020-09-15T18:50:51-03:00",
"identifier" : "COLABORADORES",
"createdAt" : ISODate("2020-09-18T18:41:00-03:00"),
"__v" : 0
},
{
"_id" : ObjectId("5f6144d7863bb40018045906"),
"status" : "BATCH_PROCESSING",
"groupId" : 13,
"type" : "not",
"finished" : false,
"scheduledTo" : "2020-09-16T19:48:00-03:00",
"identifier" : "COLABORADORES",
"createdAt" : ISODate("2020-09-15T19:48:55-03:00"),
"__v" : 0
},
{
"_id" : ObjectId("5f617021b985c1001974c3af"),
"status" : "CANCELED",
"groupId" : 13,
"type" : "not",
"finished" : true,
"scheduledTo" : "2020-09-15T23:06:00-03:00",
"identifier" : "COLABORADORES",
"createdAt" : ISODate("2020-09-18T22:53:37-03:00"),
"__v" : 0,
"numberOfLines" : 1
}]
)
Query
When applying the query in your post...
db.getCollection("batches").find(
{ createdAt : {
"$gte": ISODate("2020-09-15T00:00:00Z"),
"$lt": ISODate("2020-09-19T00:00:00Z")
} })
... we now see the following results:
MongoDB Enterprise replSet:PRIMARY> db.getCollection("batches").find(
... { createdAt : {
... "$gte": ISODate("2020-09-15T00:00:00Z"),
... "$lt": ISODate("2020-09-19T00:00:00Z")
... } })
{ "_id" : ObjectId("5f6134ecf908840018f2e9ea"), "status" : "BATCH_PROCESSING", "groupId" : 13, "type" : "not", "finished" : false, "scheduledTo" : "2020-09-15T18:50:51-03:00", "identifier" : "COLABORADORES", "createdAt" : ISODate("2020-09-18T21:41:00Z"), "__v" : 0 }
{ "_id" : ObjectId("5f6144d7863bb40018045906"), "status" : "BATCH_PROCESSING", "groupId" : 13, "type" : "not", "finished" : false, "scheduledTo" : "2020-09-16T19:48:00-03:00", "identifier" : "COLABORADORES", "createdAt" : ISODate("2020-09-15T22:48:55Z"), "__v" : 0 }

How to find and update an array in the object of array document using mongoose

A query to how to update the items array of object by
finding the breed dachshund
update the name to new-dog
updatedAt to the current time
[{
"_id" : ObjectId("60053b74aa72f132cb75b8b6"),
"clientId" : "test",
"items" : [
{
"_id" : ObjectId("60053b74aa72f132cb75b8b7"),
"name" : "tommy",
"breed" : "dachshund",
"createdAt" : 1610955636,
"updatedAt" : 1610955636
},
{
"_id" : ObjectId("60053b74aa72f132cb75b8b8"),
"name" : "mickey",
"breed" : "husky",
"createdAt" : 1610955636,
"updatedAt" : 1610955636
},
{
"_id" : ObjectId("60053b74aa72f132cb75b8b9"),
"name" : "whiskey",
"breed" : "dachshund",
"createdAt" : 1610955636,
"updatedAt" : 1610955636
},
{
"_id" : ObjectId("60053b74aa72f132cb75b8ba"),
"name" : "milo",
"breed" : "bulldog",
"createdAt" : 1610955636,
"updatedAt" : 1610955636
},
{
"_id" : ObjectId("60053b74aa72f132cb75b8bb"),
"name" : "pooh",
"breed" : "poodle",
"createdAt" : 1610955636,
"updatedAt" : 1610955636
}
],
"shopname" : "myshopify"
}]
const curDatetime = moment(moment();
model.updateOne(
{_id: ObjectId("60053b74aa72f132cb75b8b6")},
{
arrayFilters: [
{'el.breed': 'dachshund'}
]
},
{
$set: {
'items.$[el].name': 'new-dog',
'items.$[el].updatedAt': curDatetime
}
}, "multi": true)

MongoDB project with lookup

I want to get other collection's field using $lookup.
For example, this is my users collection:
{ "_id" : ObjectId("601c4f89049f9d2cc47eece2"), "username" : "Ahmad", "email" : "aaa#aaa.com", "password" : "$2a$08$fAT1G.db9LjXRV7bOPKNzuosWZ3QGJs2rdHIGmPbWtusDA0Qko47e", "tokens" : [ { "_id" : ObjectId("601d4de52472f01ef4552e77"), "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwMWM0Zjg5MDQ5ZjlkMmNjNDdlZWNlMiIsImlhdCI6MTYxMjUzMzIyMSwiZXhwIjoxNjEzMTM4MDIxfQ.lEt5mIQkjVCRFvDJsHoK1rwdN-WELSVWMFW3p8itZBU" }, { "_id" : ObjectId("601c4f89049f9d2cc47eece3"), "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwMWM0Zjg5MDQ5ZjlkMmNjNDdlZWNlMiIsImlhdCI6MTYxMjQ2ODEwNSwiZXhwIjoxNjEzMDcyOTA1fQ.WwKCenn7Qh3C1DhJT7H1Kcqu4ZRl0Z7SYJxBV6v87S8" } ], "createdAt" : ISODate("2021-02-04T19:48:25.024Z"),
"updatedAt" : ISODate("2021-02-05T13:53:41.730Z"), "__v" : 0 }
{ "_id" : ObjectId("601c954a59477b1d38e8a69e"), "username" : "fred", "email" : "isded#gmail.com", "password" : "$2a$08$nZ2kusIoSdwgjBpcZX4WTe2sO3tnieUcVIDGXiUCofLSvkdSdTRFa", "tokens" : [ { "_id" : ObjectId("601c954a59477b1d38e8a69f"), "token" : "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwMWM5NTRhNTk0NzdiMWQzOGU4YTY5ZSIsImlhdCI6MTYxMjQ4NTk2MiwiZXhwIjoxNjEzMDkwNzYyfQ.bHkhfBlgswerB25za2y3YODk-cbRgGhlcrtr-zaIG9M" } ], "createdAt" : ISODate("2021-02-05T00:46:02.518Z"), "updatedAt" : ISODate("2021-02-05T00:46:02.518Z"), "__v" : 0 }
And here posts collection:
{ "_id" : ObjectId("601c5190939a1e294c688267"), "title" : "abdulila", "content" : "wqd", "category" : "Health", "owner" : ObjectId("601c4f89049f9d2cc47eece2"), "comments" : [ {
"_id" : ObjectId("601c532a5b746f1ad081c57e"), "content" : "Marchgisio", "owner" : ObjectId("601c4f89049f9d2cc47eece2"), "createdAt" : ISODate("2021-02-04T20:03:54.055Z"), "updatedAt" : ISODate("2021-02-04T20:03:54.055Z") }, { "_id" : ObjectId("601c53445b746f1ad081c57f"), "content" : "Balotelli", "owner" : ObjectId("601c4f89049f9d2cc47eece2"), "createdAt" : ISODate("2021-02-04T20:04:20.967Z"), "updatedAt" : ISODate("2021-02-04T20:04:20.967Z") } ], "createdAt" : ISODate("2021-02-04T19:57:04.902Z"), "updatedAt" : ISODate("2021-02-04T20:04:20.968Z"), "__v" : 2 }
{ "_id" : ObjectId("601c958259477b1d38e8a6a0"), "title" : "ohh mighty spurs", "content" : "harry kane", "category" : "Sports", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "comments" : [ { "_id" : ObjectId("601c958f59477b1d38e8a6a1"), "content" : "eorje", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "createdAt" : ISODate("2021-02-05T00:47:11.461Z"), "updatedAt" : ISODate("2021-02-05T00:47:11.461Z") }, { "_id" : ObjectId("601c95cac3b0131328e29344"), "content" : "qwe", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "createdAt" : ISODate("2021-02-05T00:48:10.207Z"), "updatedAt" : ISODate("2021-02-05T00:48:10.207Z") }, { "_id" : ObjectId("601c95e3af31ab1608abd23f"), "content" : "wef", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "createdAt" : ISODate("2021-02-05T00:48:35.168Z"), "updatedAt" : ISODate("2021-02-05T00:48:35.168Z") } ], "createdAt" : ISODate("2021-02-05T00:46:58.962Z"), "updatedAt" : ISODate("2021-02-05T00:48:35.168Z"), "__v" : 3 }
{ "_id" : ObjectId("601d210fbf41fd262c9172c4"), "title" : "bobo", "content" : "hiv is a lie and in god name we will kill all the jews in balastin XD UwU\n", "category" : "Movies", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "comments" : [ ], "createdAt" : ISODate("2021-02-05T10:42:23.773Z"), "updatedAt" : ISODate("2021-02-05T10:42:23.773Z"), "__v"
: 0 }
{ "_id" : ObjectId("601d4a2f1f169d3d9cbfcbfe"), "title" : "Abdallah", "content" : "dfsv", "category" : "Health", "owner" : ObjectId("601c954a59477b1d38e8a69e"), "comments" : [ { "_id" : ObjectId("601d50d80678f626105f943e"), "content" : "dvd", "owner" : ObjectId("601c4f89049f9d2cc47eece2"), "createdAt" : ISODate("2021-02-05T14:06:16.941Z"), "updatedAt"
: ISODate("2021-02-05T14:06:16.941Z") }, { "_id" : ObjectId("601d531fcc80c13fb832af40"), "content" : "svsf", "owner" : ObjectId("601c4f89049f9d2cc47eece2"), "createdAt" : ISODate("2021-02-05T14:15:59.873Z"), "updatedAt" : ISODate("2021-02-05T14:15:59.873Z") } ], "createdAt" : ISODate("2021-02-05T13:37:51.787Z"), "updatedAt" : ISODate("2021-02-05T14:15:59.874Z"), "__v" : 2 }
My purpose is to get all comments of 1 specific post. Then, for each comment - I want its content and owner username.
This is my try:
Post.aggregate([
{
$match: { _id: mongoose.Types.ObjectId(req.query.postID) },
},
{
$limit: 1,
},
{
$project: {
_id: 0,
'comments.owner': 1,
'comments.content': 1,
},
},
]);
So this gives me back the content and the owner id. But I want the owner username which presents in the users collection. How could I achieve this?
I came up with this pipeline. I'm sure it cloud be improve.
The steps are (commented in the pipeline)
Split comments array so we could concentrate on each one
Lookup for the user info
The lookup brings an array of one element, so I unwind it.
Replace the owner object id with the owner username.
Group comments
Project the needed fields
I test this directly on mongodb with one of your post.
[
{
$match: { _id: ObjectId("601d4a2f1f169d3d9cbfcbfe") },
},
{
$unwind: '$comments' //split comments array so we could concentrate on each one
},
{
$lookup: {
from: 'user',
localField: 'comments.owner', // lookup for the user info
foreignField: '_id',
as: 'owner'
}
},
{
$unwind: '$owner' // the lookup brings an array of one element, so I unwind it.
},
{
$addFields: {
'comments.owner': "$owner.username" //replace the owner object id with the owner username
}
},
{
$group: {
_id: '_id', // group comments
'comments': {$push: '$comments'}
}
},
{
$project:{
_id: 0, // project the needed fields
'comments.content':1,
'comments.owner': 1,
}
}
])

Deleting an object inside another object in Mongodb and for GOlang

I wanna delete a specific object inside an object, My object:
{
"_id" : ObjectId("5f577f3cce031ee00f5e32c9"),
"UserId" : 0,
"firstname" : "user 1",
"lastname" : "user 1",
"finishedTrainings" : [
{
"itemId" : 3,
"validationScore" : 1,
"timestamps" : {
"createdat" : ISODate("2020-09-09T12:57:31.275Z"),
"createdby" : 0,
"updatedat" : ISODate("0001-01-01T00:00:00Z"),
"updatedby" : 0
},
"isValidated" : true
},
{
"itemId" : 0,
"validationScore" : 0.6666666666666666,
"timestamps" : {
"createdat" : ISODate("2020-09-09T12:59:04.268Z"),
"createdby" : 0,
"updatedat" : ISODate("0001-01-01T00:00:00Z"),
"updatedby" : 0
},
"isValidated" : true
}
],
"biography" : ""
}
and I wanna delete the finishedTraining(id=3),what would be the syntax in mongodb
//code output from mongo shell 4.2, windows10
//data set as given in problem statement
> db.userTraining.find().pretty();
{
"_id" : ObjectId("5f577f3cce031ee00f5e32c9"),
"UserId" : 0,
"firstname" : "user 1",
"lastname" : "user 1",
"finishedTrainings" : [
{
"itemId" : 3,
"validationScore" : 1,
"timestamps" : {
"createdat" : ISODate("2020-09-09T12:57:31.275Z"),
"createdby" : 0,
"updatedat" : ISODate("0001-01-01T00:00:00Z"),
"updatedby" : 0
},
"isValidated" : true
},
{
"itemId" : 0,
"validationScore" : 0.6666666666666666,
"timestamps" : {
"createdat" : ISODate("2020-09-09T12:59:04.268Z"),
"createdby" : 0,
"updatedat" : ISODate("0001-01-01T00:00:00Z"),
"updatedby" : 0
},
"isValidated" : true
}
],
"biography" : ""
}
//assuming objectID is unique for the document, you can query your own business field
> db.userTraining.update(
... {_id:ObjectId("5f577f3cce031ee00f5e32c9")},
... {$pull:{"finishedTrainings":{itemId:3}}},
... false,
... true
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.userTraining.find().pretty();
{
"_id" : ObjectId("5f577f3cce031ee00f5e32c9"),
"UserId" : 0,
"firstname" : "user 1",
"lastname" : "user 1",
"finishedTrainings" : [
{
"itemId" : 0,
"validationScore" : 0.6666666666666666,
"timestamps" : {
"createdat" : ISODate("2020-09-09T12:59:04.268Z"),
"createdby" : 0,
"updatedat" : ISODate("0001-01-01T00:00:00Z"),
"updatedby" : 0
},
"isValidated" : true
}
],
"biography" : ""
}
>
//above id=3 is deleted object from the array, other document object remain intact by using "$pull" in the update statement

Add additional properties to the output json

There is a collection of User
{
"_id" : ObjectId("5a0d45ca8af3a91847b7cf95"),
"updatedAt" : ISODate("2017-11-16T09:34:14.651Z"),
"createdAt" : ISODate("2017-11-16T08:01:14.119Z"),
"name" : "John",
"email" : "test1#gmail.com",
"groupsFavorite" : [
ObjectId("5a0d45db8af3a91847b7cf96")
],
"groups" : [
ObjectId("5a0d45db8af3a91847b7cf96"),
ObjectId("5a0d45e18af3a91847b7cf97")
],
"__v" : 3
}
There is a collection of Groups
/* 1 */
{
"_id" : ObjectId("5a0d45db8af3a91847b7cf96"),
"updatedAt" : ISODate("2017-11-16T08:01:31.815Z"),
"createdAt" : ISODate("2017-11-16T08:01:31.815Z"),
"userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
"title" : "New title",
"slug" : "new-title-1",
"description" : "Lorem",
"__v" : 0
}
/* 2 */
{
"_id" : ObjectId("5a0d45e18af3a91847b7cf97"),
"updatedAt" : ISODate("2017-11-16T08:01:37.005Z"),
"createdAt" : ISODate("2017-11-16T08:01:37.005Z"),
"userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
"title" : "New title",
"slug" : "new-title-2",
"description" : "Lorem",
"__v" : 0
}
/* 3 */
{
"_id" : ObjectId("5a0d5cb0cd59342da943d55a"),
"updatedAt" : ISODate("2017-11-16T09:38:56.912Z"),
"createdAt" : ISODate("2017-11-16T09:38:56.912Z"),
"userId" : ObjectId("5a0d5c48cd59342da943d559"),
"title" : "New title",
"slug" : "new-title-3",
"description" : "Lorem",
"__v" : 0
}
There is a method that returns groups of a particular user.
It is necessary to add these data to the new property of favorite: true or false for building a table.
For example:
{
"_id" :"5a0d45db8af3a91847b7cf96",
"updatedAt" : "2017-11-16T08:01:31.815Z",
"createdAt" : "2017-11-16T08:01:31.815Z",
"userId" : "5a0d45ca8af3a91847b7cf95",
"title" : "New title",
"slug" : "new-title-1",
"description" : "Lorem",
"favorite": "true"
},
{
"_id" : "5a0d45e18af3a91847b7cf97",
"updatedAt" : "2017-11-16T08:01:37.005Z",
"createdAt" : "2017-11-16T08:01:37.005Z",
"userId" : "5a0d45ca8af3a91847b7cf95",
"title" : "New title",
"slug" : "new-title-2",
"description" : "Lorem",
"favorite": "false"
},
{
"_id" : "5a0d5cb0cd59342da943d55a",
"updatedAt" : "2017-11-16T09:38:56.912Z",
"createdAt" : "2017-11-16T09:38:56.912Z",
"userId" : "5a0d5c48cd59342da943d559",
"title" : "New title",
"slug" : "new-title-3",
"description" : "Lorem",
"favorite": "false"
}
You can use $lookup operator for checking the _id and userId fields in "User" collection. And also for determining it is in or not, you can use $eq operator.
db.getCollection('Groups').aggregate([
{
$lookup:
{
from: "User",
localField: "_id",
foreignField: "groupsFavorite",
as: "FavoriteByGrp"
}
}
,{
$lookup:
{
from: "User",
localField: "userId",
foreignField: "_id",
as: "FavoriteByUsr"
}
}
,{
"$project":
{
_id:1,
updatedAt:1,
createdAt:1,
userId:1,
title:1,
slug:1,
description:1,
favorite:
{
"$cond":
{
if: { "$eq": [ "$FavoriteByGrp._id", "$FavoriteByUsr._id" ] },
then: "true",
else: "false"
}
}
}
}
])
Result:
/* 1 */
{
"_id" : ObjectId("5a0d45db8af3a91847b7cf96"),
"updatedAt" : ISODate("2017-11-16T08:01:31.815Z"),
"createdAt" : ISODate("2017-11-16T08:01:31.815Z"),
"userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
"title" : "New title",
"slug" : "new-title-1",
"description" : "Lorem",
"favorite" : "true"
}
/* 2 */
{
"_id" : ObjectId("5a0d45e18af3a91847b7cf97"),
"updatedAt" : ISODate("2017-11-16T08:01:37.005Z"),
"createdAt" : ISODate("2017-11-16T08:01:37.005Z"),
"userId" : ObjectId("5a0d45ca8af3a91847b7cf95"),
"title" : "New title",
"slug" : "new-title-2",
"description" : "Lorem",
"favorite" : "false"
}
/* 3 */
{
"_id" : ObjectId("5a0d5cb0cd59342da943d55a"),
"updatedAt" : ISODate("2017-11-16T09:38:56.912Z"),
"createdAt" : ISODate("2017-11-16T09:38:56.912Z"),
"userId" : ObjectId("5a0d5c48cd59342da943d559"),
"title" : "New title",
"slug" : "new-title-3",
"description" : "Lorem",
"favorite" : "false"
}