Okay, so find cannot do this. But there is a kind of obscure way to get the result using aggregate. So assuming you have a creatorId
variable somewhere that is your Id:
db.collection.aggregate([
// Match your posts
{ "$match": { "creatorId": creatorId },
// Unwind the array
{ "$unwind": "$replies" },
// Project the fields you want, notice the logical conditions
{ "$project": {
"category": 1,
"location": 1,
"isMine": { "$eq": [ "$creatorId", creatorId ] },
"answerIsMine": { "$eq": [
"$replies.creatorId",
creatorId
]}
}},
// Group on the unique document, get sum and max value
{ "$group": {
"_id": {
"_id": "$_id",
"category": "$category",
"location": "$location",
"isMine": "$isMine",
},
"replies": { "$sum": 1 },
"OneAnswerIsMine": { "$max": "$answerIsMine" }
}},
// Nicer Output
{ "$project": {
"_id": "$_id._id",
"category": "$_id.category",
"location": "$_id.location",
"isMine": "$_id.isMine",
"replies": 1,
"OneAnswerIsMine": 1
}}
])
Apart from the other things, your "custom fields" were generated by using the logical $eq
operator. Here we compare the field value of creatorId
to the variable value for you that you have stored. When they are "equal" then the condition is true
, otherwise it is false
.
So, therefore welcome to aggregation. That is a very powerful tool to get the results that you want and you can not only "group" things together, but otherwise transform the document into the form that you want
See your driver documentation for the language details ( presented here is JSON for everyone ), but you are basically forming BSON documents as each stage of the pipeline.