无法查询MongoDB

huangapple go评论74阅读模式
英文:

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}}}}

huangapple
  • 本文由 发表于 2021年6月29日 20:09:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/68178441.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定