Given an object like this, how can I make it lookup users info only if the isAnonymous
field is false
?
{
"_id" : ObjectId(""),
"user" : ObjectId(""),
"title" : "This is an idea",
"shortDescription" : "Pretty cool stuff",
"downVoteCount" : NumberInt(0),
"upVoteCount" : NumberInt(12),
"voteTotalCount" : NumberInt(12),
"deleted" : false,
"ideaNumber" : NumberInt(5),
"isAnonymous" : false,
"created" : ISODate("2018-01-19T23:37:10.949+0000")
}
Here is my current query:
db.ideas.aggregate(
{
$match: { "deleted": false }
},
{
$lookup: {
"from" : "users",
"localField" : "user",
"foreignField" : "_id",
"as" : "user"
}
},
{
$unwind: {
path : "$user",
includeArrayIndex : "arrayIndex", // optional
preserveNullAndEmptyArrays : false // optional
}
},
{
$project: {
"ideaNumber": 1,
"title": 1,
"isAnonymous": 1,
"shortDescription": 1,
"upVoteCount": 1,
"created": 1,
"user.email": 1,
"user.name": 1,
"user.createdAt": 1
}
},
);
Yields an object like this:
{
"_id" : ObjectId(""),
"user" : {
"createdAt" : ISODate("2018-01-19T21:50:02.758+0000"),
"email" : "blah",
"name" : "Foo Bar"
},
"title" : "This is an idea",
"shortDescription" : "Pretty cool stuff",
"upVoteCount" : NumberInt(12),
"ideaNumber" : NumberInt(5),
"isAnonymous" : false,
"created" : ISODate("2018-01-19T23:37:10.949+0000")
}
I'd like to see the object like this instead
{
"_id" : ObjectId(""),
"user" : {
"createdAt" : "anonymous",
"email" : "anonymous",
"name" : "anonymous"
},
"title" : "This is an idea",
"shortDescription" : "Pretty cool stuff",
"upVoteCount" : NumberInt(12),
"ideaNumber" : NumberInt(5),
"isAnonymous" : false,
"created" : ISODate("2018-01-19T23:37:10.949+0000")
}