我有一个以下格式的收藏集。
{
"_id": "ffffc446-f33d",
"className": "com.ezdx.vist.model.Visit",
"organizationId": "0a0beff7-fe1e-4ab7",
"centerId": "9aef68fe-dffd-4a7d-b0ee-f8dd3fc03303",
"tests": [{
"result": 157,
"type": "PHYSICAL",
**"name": "HEIGHT",**
"consumableQuantity": 0,
"testCost": 0,
"testExpenseConsumable": 0
},
{
"result": 8,
"type": "RDT",
**"name": "URIC",**
"consumableQuantity": 0,
"testCost": 0,
"testExpenseConsumable": 0
}
],
"repeatVisit": true
}
我想要集合test.name =“ Uric”并具有特定列。
{
"result": 8,
"type": "RDT",
**"name": "Uric",**
"consumableQuantity": 0,
"testCost": 0,
"testExpenseConsumable": 0
}
我设法以所需的方式进行收藏,但无法获得所需的格式。 以下是我的查询
db.visits.aggregate( [ { $unwind : "$tests" },
{ $match: { $and: [{"tests.name":"URIC"}]
} } ] )
答案 0 :(得分:1)
尝试以下操作:$replaceWith(= v4.2)或$replaceRoot(> = v3.4)
db.visits.aggregate([
{
$unwind: "$tests"
},
{
$match: {
"tests.name": "URIC"
}
},
{
$replaceWith: "$tests"
}
])
答案 1 :(得分:1)
作为Valijon答案的替代方法,可以使用$filter聚合,这可能会更快,因为我们没有应用$ unwind。
db.collection.aggregate([
{
$project: {
items: {
$filter: {
input: "$tests",
as: "item",
cond: {
$eq: [
"$$item.name",
"URIC"
]
}
}
}
}
},
{
$replaceRoot: {
newRoot: {
$arrayElemAt: [
"$items",
0
]
}
}
}
])