我有以下檔案資訊。
[
{
_id: ObjectId("61d67f0a74ec8620f34c57ed"),
shot: [
{
shotId: "undefinedMKSf*Tf#!qHxWpz1hPzUBTz%",
clubType: "driver",
shotCount: 20,
unit: "meter",
_id: ObjectId("61d67f0a74ec8620f34c57ef"),
createdAt: ISODate("2022-01-06T05:32:58.391Z")
},
{
shotId: "undefinedMKSf*Tf#!qHxWpz1hPzUBTz%",
clubType: "wood",
shotCount: 20,
unit: "meter",
_id: ObjectId("61d67f0a74ec8620f34c57f0"),
createdAt: ISODate("2022-01-08T05:32:58.391Z")
},
{
shotId: "undefinedMKSf*Tf#!qHxWpz1hPzUBTz%",
clubType: "wood",
shotCount: 15,
unit: "yard",
_id: ObjectId("61d67f0a74ec8620f34c57f0"),
createdAt: ISODate("2022-01-08T05:32:58.391Z")
},
{
shotId: "undefinedMKSf*Tf#!qHxWpz1hPzUBTz%",
clubType: "wood",
shotCount: 15,
unit: "yard",
_id: ObjectId("61d67f0a74ec8620f34c57f0"),
createdAt: ISODate("2022-01-08T05:32:58.391Z")
}
]
}
]
在上面的檔案中,我怎樣才能只找到帶有clubTypeof wood、shotCountof15和unitof 的檔案yard?
我寫了如下查詢陳述句,但沒有出現預期的結果。
db.collection.aggregate([
{
"$match": {
_id: ObjectId("61d67f0a74ec8620f34c57ed"),
"shot.clubType": "wood",
shot: {
$elemMatch: {
$and: [
{
"createdAt": {
$gte: ISODate("2022-01-07T05:32:58.391Z")
}
},
{
"createdAt": {
$lte: ISODate("2022-01-09T05:32:58.391Z")
}
}
]
}
}
}
},
{
"$set": {
shot: {
"$filter": {
"input": "$shot",
"as": "s",
"cond": {
$and: [
{
"$eq": [
"$$s.clubType",
"wood"
]
},
{
"$gte": [
"$$s.createdAt",
ISODate("2022-01-07T05:32:58.391Z")
]
},
{
"$lte": [
"$$s.createdAt",
ISODate("2022-01-09T05:32:58.391Z")
]
}
]
}
}
}
}
}
])
如何修改查詢陳述句?
- 參考鏈接:[MongoPlayGround]
uj5u.com熱心網友回復:
$project在聚合末尾添加
db.collection.aggregate([
{
"$match": {
_id: ObjectId("61d67f0a74ec8620f34c57ed"),
"shot.clubType": "wood",
shot: {
$elemMatch: {
$and: [
{
"createdAt": {
$gte: ISODate("2022-01-07T05:32:58.391Z")
}
},
{
"createdAt": {
$lte: ISODate("2022-01-09T05:32:58.391Z")
}
}
]
}
}
}
},
{
"$set": {
shot: {
"$filter": {
"input": "$shot",
"as": "s",
"cond": {
$and: [
{
"$eq": [
"$$s.clubType",
"wood"
]
},
{
"$gte": [
"$$s.createdAt",
ISODate("2022-01-07T05:32:58.391Z")
]
},
{
"$lte": [
"$$s.createdAt",
ISODate("2022-01-09T05:32:58.391Z")
]
}
]
}
}
}
}
},
{
"$project": {
"shot.clubType": 1,
"shot.shotCount": 1,
"shot.unit": 1
}
}
])
mongoplayground
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/414128.html
標籤:
上一篇:如何在貓鼬的陣列中找到物件?
下一篇:如何更新貓鼬中的數字陣列
