'How can I project a field that is inside an object in mongodb
I'm using "sample_mflix" database provided by mongo atlas and mongodb vs code extension to practice. My code looks like this so far:
use('sample_mflix');
db.movies.aggregate([
{
$lookup: {
from: 'comments',
localField: '_id',
foreignField: 'movie_id',
as: 'comments'
},
},
{$unwind: '$comments'},
{
$project:{
comments:'$comments',
_id:0
}
},
{
$project:{
name:'$comments.name',
email:'$comments.email',
date:'$comments.date',
}
},
])
And this is the result I get from it:
[
{
"name": "Taylor Scott",
"email": "[email protected]",
"date": {
"$date": "1970-11-15T05:54:02Z"
}
},
{
"name": "Jaqen H'ghar",
"email": "[email protected]",
"date": {
"$date": "1981-11-08T04:32:25Z"
}
},
{
"name": "Yara Greyjoy",
"email": "[email protected]",
"date": {
"$date": "2012-11-26T11:00:57Z"
}
}
.
.
.]
As you can see, the date field is an object in this document, but I want to bring with $project only the string value of the date which is in the $date field, like this:
{
"name": "Yara Greyjoy",
"email": "[email protected]",
"date": "2012-11-26T11:00:57Z"
}
How can I achieve it ?
Solution 1:[1]
Use $toString
db.collection.aggregate([
{
$set: {
date: {
$toString: "$date"
}
}
}
])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | YuTing |
