MongoDb Пост форматирование агрегации $lookup с ограниченными данными
У меня есть 2 коллекции coll1 и coll2. Я хочу применить $lookup к полям "_id" и "comm_field", поэтому я использовал запрос:
db.coll1.aggregate([
{
$lookup:
{
from: "coll2",
localField: "_id",
foreignField: "comm_field",
as: "inventory_docs"
}
},
{
$project:{"_id" : 0, "inventory_docs" : 1}
},
{ $unwind:"$inventory_docs"}
])
И получите вывод как:
/* 1 */
{
"inventory_docs" : {
"_id" : ObjectId("ssdfsfsdfsdfsfsdfsdfsdfsfsdf"),
"comm_field" : NumberLong(1111),
"status" : "active"
}
}
/* 2 */
{
"inventory_docs" : {
"_id" : ObjectId("erteterterterterterterterter"),
"comm_field" : NumberLong(1111),
"status" : "active"
}
}
/* 3 */
{
"inventory_docs" : {
"_id" : ObjectId("vbvbfvbdbbcvbvcbcdrgvbcbcbcv"),
"comm_field" : NumberLong(2222),
"status" : "active"
}
}
Есть ли способ, которым я могу увидеть вывод, как:
{
"_id" : ObjectId("ssdfsfsdfsdfsfsdfsdfsdfsfsdf"),
"comm_field" : NumberLong(1111),
"status" : "active"
}
{
"_id" : ObjectId("erteterterterterterterterter"),
"comm_field" : NumberLong(1111),
"status" : "active"
}
{
"_id" : ObjectId("vbvbfvbdbbcvbvcbcdrgvbcbcbcv"),
"comm_field" : NumberLong(2222),
"status" : "active"
}
Поэтому я хочу, чтобы мои выходные данные были в формате {---}, а не в {"inventory_docs":{---}}
1 ответ
Ответ Нейла сработал. Добавление { $replaceRoot: { newRoot: "$inventory_docs" } }
сделал работу. Спасибо, Нил.
db.coll1.aggregate([
{
$lookup:
{
from: "coll2",
localField: "_id",
foreignField: "comm_field",
as: "inventory_docs"
}
},
{
$project:{"_id" : 0, "inventory_docs" : 1}
},
{ $unwind:"$inventory_docs"},
{ $replaceRoot: { newRoot: "$inventory_docs" } }
])