无法查询MongoDB

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

Unable to Query MongoDB

问题

Mongodb查询:

  1. db.products.aggregate([
  2. {
  3. $match : {
  4. "_id" : ObjectId("60d95b5ab861ccc04fd4b598")
  5. }
  6. },
  7. {
  8. $project: {
  9. title : "Test Product 10",
  10. offers: {
  11. $filter: {
  12. input: "$offers",
  13. as: "offers",
  14. cond: {
  15. $eq: [ "$$offers.active", true ]
  16. }
  17. }
  18. }
  19. }
  20. }
  21. ]).pretty()

Golang查询:

  1. productMatch := bson.D{{"$match", bson.M{"_id": objID}}}
  2. project := bson.D{{"$project", bson.D{{"offers", bson.D{{"$filter", bson.D{{
  3. "input", "$offers"}, {"as", "offers"}, {"cond", bson.D{{
  4. "$eq", bson.D{{"$$offers.active", true}}}}}}}}}}}}
  5. pipeLine := mongo.Pipeline{productMatch, project}
  6. result, err := s.DB.Collection(collectionProducts).Aggregate(context.TODO(), pipeLine)
英文:

Mongodb query:

  1. db.products.aggregate([
  2. {
  3. $match : {
  4. "_id" : ObjectId("60d95b5ab861ccc04fd4b598")
  5. }
  6. },
  7. {
  8. $project: {
  9. title : "Test Product 10",
  10. offers: {
  11. $filter: {
  12. input: "$offers",
  13. as: "offers",
  14. cond: {
  15. $eq: [ "$$offers.active", true ]
  16. }
  17. }
  18. }
  19. }
  20. }
  21. ]).pretty()

Golang Query:

  1. productMatch := bson.D{{"$match", bson.M{"_id": objID}}}
  2. project := bson.D{{"$project", bson.D{{"offers", bson.D{{"$filter", bson.D{{
  3. "input", "$offers"}, {"as", "offers"}, {"cond", bson.D{{
  4. "$eq", bson.D{{"$$offers.active", true}}}}}}}}}}}}
  5. pipeLine := mongo.Pipeline{productMatch, project}
  6. result, err := s.DB.Collection(collectionProducts).Aggregate(context.TODO(), pipeLine)

答案1

得分: 1

这部分代码:

  1. cond: {
  2. $eq: [ "$$offers.active", true ]
  3. }

$eq 的值是一个数组。bson.D 用于表示文档。要表示一个数组,请使用 bson.A

所以,将代码修改为:

  1. { "cond", bson.D{
  2. { "$eq", bson.A{ "$$offers.active", true } }
  3. }}
英文:

This part:

  1. cond: {
  2. $eq: [ "$$offers.active", true ]
  3. }

The value for $eq is an array. bson.D is to model documents. To model an array, use bson.A.

So instead of:

  1. {"cond", bson.D{{
  2. "$eq", bson.D{{"$$offers.active", true}}}}}

Use

  1. {"cond", bson.D{{
  2. "$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:

确定