在MongoDB中查找文档并仅返回具有特定值的数组元素



我试图在一个数组中找到一个值,在一个文档中,并只返回数组索引的数组值,在那里找到了该值,以及外部文档数据。

这是集合中的一个示例文档。

{
"_id": {
"$oid": "63452345f14f98447b792327e9c"
},
"TID": "695742332",
"DID": "WW*DHD",
"IndexedSpansUsageCost": [
{
"month": {
"$numberInt": "9"
},
"year": "2022",
"IndexedSpansCost": {
"$numberDouble": "1.11"
},
"IndexedSpansCount": {
"$numberDouble": "418334.0"
}
},
{
"month": {
"$numberInt": "10"
},
"year": "2022",
"IndexedSpansCost": {
"$numberDouble": "1.11"
},
"IndexedSpansCount": {
"$numberDouble": "432516.0"
}
}
]
}

我能够找到月份为9的特定文档,但输出的是整个文档,包括月份为10、11等的数组。

我试过下面的代码

multifilter := bson.A{{"IndexedSpansUsageCost.month", bson.D{{"$eq", 9}}}}
cursor, err := collection.Find(context.TODO(), multifilter)
if err != nil {
panic(err)
}
// end find
var resultsTest3 []bson.M
if err = cursor.All(context.TODO(), &resultsTest3); err != nil {
panic(err)
}
for _, resultTest3 := range resultsTest3 {
output, err := json.MarshalIndent(resultTest3, "", "    ")
if err != nil {
panic(err)
}
fmt.Printf("%sn", output)
}

我也试过聚合,但还没有得到这个工作正常。

我希望只得到以下数据。

{
"_id": {
"$oid": "63452345f14f98447b792327e9c"
},
"TID": "695742332",
"DID": "WW*DHD",
"IndexedSpansUsageCost": [
{
"month": {
"$numberInt": "9"
},
"year": "2022",
"IndexedSpansCost": {
"$numberDouble": "1.11"
},
"IndexedSpansCount": {
"$numberDouble": "418334.0"
}
}
]
}

真的很难找到如何获得我正在寻找的数组值。我看到的每个示例都返回整个文档和所有数组值,而不仅仅是找到值的数组。

matchStage  := bson.D{{"$match", bson.D{{"IndexedSpansUsageCost.month", "9"}}}}
unwind  := bson.D{{"$unwind", "$IndexedSpansUsageCost"}}
matchAgain  := bson.D{{"$match", bson.D{{"IndexedSpansUsageCost.month", "9"}}}}

cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{matchStage, unwind, matchAgain})
if err != nil {
panic(err)
}
// end find
var resultsTest3 []bson.M
if err = cursor.All(context.TODO(), &resultsTest3); err != nil {
panic(err)
}
for _, resultTest3 := range resultsTest3 {
output, err := json.MarshalIndent(resultTest3, "", "    ")
if err != nil {
panic(err)
}
fmt.Printf("%sn", output)
}

最新更新