英文:
Unable to Query MongoDB
问题
Mongodb查询:
db.products.aggregate([
{
$match : {
"_id" : ObjectId("60d95b5ab861ccc04fd4b598")
}
},
{
$project: {
title : "Test Product 10",
offers: {
$filter: {
input: "$offers",
as: "offers",
cond: {
$eq: [ "$$offers.active", true ]
}
}
}
}
}
]).pretty()
Golang查询:
productMatch := bson.D{{"$match", bson.M{"_id": objID}}}
project := bson.D{{"$project", bson.D{{"offers", bson.D{{"$filter", bson.D{{
"input", "$offers"}, {"as", "offers"}, {"cond", bson.D{{
"$eq", bson.D{{"$$offers.active", true}}}}}}}}}}}}
pipeLine := mongo.Pipeline{productMatch, project}
result, err := s.DB.Collection(collectionProducts).Aggregate(context.TODO(), pipeLine)
英文:
Mongodb query:
db.products.aggregate([
{
$match : {
"_id" : ObjectId("60d95b5ab861ccc04fd4b598")
}
},
{
$project: {
title : "Test Product 10",
offers: {
$filter: {
input: "$offers",
as: "offers",
cond: {
$eq: [ "$$offers.active", true ]
}
}
}
}
}
]).pretty()
Golang Query:
productMatch := bson.D{{"$match", bson.M{"_id": objID}}}
project := bson.D{{"$project", bson.D{{"offers", bson.D{{"$filter", bson.D{{
"input", "$offers"}, {"as", "offers"}, {"cond", bson.D{{
"$eq", bson.D{{"$$offers.active", true}}}}}}}}}}}}
pipeLine := mongo.Pipeline{productMatch, project}
result, err := s.DB.Collection(collectionProducts).Aggregate(context.TODO(), pipeLine)
答案1
得分: 1
这部分代码:
cond: {
$eq: [ "$$offers.active", true ]
}
$eq
的值是一个数组。bson.D
用于表示文档。要表示一个数组,请使用 bson.A
。
所以,将代码修改为:
{ "cond", bson.D{
{ "$eq", bson.A{ "$$offers.active", true } }
}}
英文:
This part:
cond: {
$eq: [ "$$offers.active", true ]
}
The value for $eq
is an array. bson.D
is to model documents. To model an array, use bson.A
.
So instead of:
{"cond", bson.D{{
"$eq", bson.D{{"$$offers.active", true}}}}}
Use
{"cond", bson.D{{
"$eq", bson.A{"$$offers.active", true}}}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论