After I execute aggregate, I have following data:
{
"_id" : ObjectId("61ea385114e22e000c58a502"),
"stu_id" : "h224566378",
"stu_inf" : [
{
"_id" : ObjectId("61ea3a35c34a334514e7e8df"),
"stu_id" : "h224566378",
"gender" : "male",
"class" : "A",
}
]
}
If I want data to be the following:
{
"_id" : ObjectId("61ea385114e22e000c58a502"),
"stu_id" : "h224566378",
"stu_class" : "A"
}
How to use "aggregate" to get my needs?
I want the "class value" in the extracted "stu_inf" to become the value of the new field.
I try following way, it can get the result:
db.collection_name.aggregete([
...
{"$project": {"stu_id": 1, "stu_class": "$stu_inf.class"}},
{"$unwind": "$stu_class"}
])
but I wonder if there is any other way?
CodePudding user response:
Use $first
db.collection.aggregate([
{
$project: {
"stu_id": 1,
"stu_class": {
$first: "$stu_inf.class"
}
}
}
])