[英]How can I change an array of documents to an array of values in MongoDB shell?
[英]How can I count the documents in an array depending on their value in mongodb?
我需要計算_id的停車位數量:5d752c544f4f1c0f1c93eb23,該屬性在排除屬性中具有錯誤值,如何安裝查詢?
到目前為止,我已經能夠選擇排除屬性為false的停車位數量。 但是正在從所有停車場中選擇
請注意,有兩個文檔代表一個停車場,每個文檔都有一個稱為parkingSpaces的數組,用於記錄停車位文檔。
第一個文檔有2個空缺不被排除,因此排除了該屬性:false,第二個文檔只有一個空缺,也沒有被排除。
{
"_id": "5d752c544f4f1c0f1c93eb23",
"name": "estacionamento um",
"parkingSpace": [
{
"_id": "5d752cf54f4f1c0f1c93eb26",
"name": "vg001",
"excluded": true
},
{
"_id": "5d752cf54f4f1c0f1c93eb27",
"name": "vg001",
"excluded": false
},
{
"_id": "5d75339bc411423a9c14ac52",
"name": "vg002",
"excluded": false
}
]
},
{
"_id": "5d7706b60d354b72388a38f4",
"name": "estacionamento dois",
"parkingSpace": [
{
"_id": "5d77078a5173bb63bc87b7ca",
"name": "vg004",
"excluded": false
}
]
}
我需要添加停車位_id:5d752c544f4f1c0f1c93eb23,其排除屬性中的值為false。
最后,我需要返回值2,請參考_id:5d752c544f4f1c0f1c93eb23停車位,這些車位在排除屬性中的值為false。
到目前為止,通過以下查詢,我能夠選擇具有false值的排除屬性的空缺,但它是從所有停車場中選擇的。
const registeredParkingSpaces = await Parking.aggregate([
{ $unwind: '$parkingSpace' },
{ $match: { 'parkingSpace.excluded': false } },
{
$group: {
_id: parking_id,
total: { $sum: 1 }
}
}
]);
返回:
{
"message": [
{
"_id": "5d752c544f4f1c0f1c93eb23",
"total": 3
}
]
}
但是它需要返回:
{
"message": [
{
"_id": "5d752c544f4f1c0f1c93eb23",
"total": 2
}
]
}
這是查詢,您可以通過該查詢獲得總停車次數。
** 更新 **
db.collection.aggregate([
{
$match: {
"parkingSpace.excluded": false,
}
},
{
$project: {
parkingSpace: 1
}
},
{
"$group": {
"_id": "$_id",
"count": {
"$sum": {
"$size": {
"$filter": {
"input": "$parkingSpace",
"as": "el",
"cond": {
"$eq": [
"$$el.excluded",
false
]
}
}
}
}
}
}
}
])
在聚合1中,您將與id匹配,然后進行下一步,您將獲得所需的計數,因為此時您正在考慮整個文檔“ parkingSpace”。 以下是示例代碼,我想它將為您工作
const ObjectId = require('mongoose').Types.ObjectId;
const registeredParkingSpaces = await Parking.aggregate([
{ $match: { _id: objectId(body.id) } }
{ $unwind: '$parkingSpace' },
{ $match: { 'parkingSpace.excluded': false } },
{
$group: {
_id: parking_id,
total: { $sum: 1 }
}
}
]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.