[MongodB] 추출 조건에 룩업과 결합된 목표를 포함하는 컬렉션 라이브러리

12742 단어 MongoDBgolangtech

개요


기존[Mongodb] 룩업으로 결합된 소장 결과를sort 또는 limit 테스트로 글에서는 컬렉션으로서의 결합 기능lookup의 기능을 소개했다.
이번에 소개된 것은 lookup 중 결합된 소장품을 추출 조건에 포함하는 실복이다.(Golang으로 설치)

하고 싶은 일


먼저 얻고자 하는 결과는 다음과 같은 구조로 가정한다.
type ItemResponse struct {
  ID              string            `json:"_id" bson:"_id"`
  Name            string            `json:"name" bson:"name"`
  Detail          string            `json:"detail" bson:"detail"`
  ShopID          string            `json:"shop_id" bson:"shop_id"`
  ShopName        string            `json:"shop_name" bson:"shop_name"`
}
합병원의 소장item은 다음과 같다shop_id.
type Item struct {
  ID              string            `json:"_id" bson:"_id"`
  Name            string            `json:"name" bson:"name"`
  Detail          string            `json:"detail" bson:"detail"`
  ShopID          string            `json:"shop_id" bson:"shop_id"`
}
합병 후 수장고shop에 점포의 정보를 저장한다.
type Shop struct {
  ID              string            `json:"_id" bson:"_id"`
  Name            string            `json:"name" bson:"name"`
}
이번 구상 키워드 검색은 itemname 또는 shopsname와 일치하는 문서를 추출합니다.

샘플


룩업으로 결합한 후 샵unwind을 한 번 하고 추출 조건을 설정한다는 방침이다.나는 Select with sub query의 보도도 참고가 될 수 있다고 생각한다.
sample.go
// 接続処理は省略・・・
col := c.Database(os.Getenv("DB_NAME")).Collection("item")

// lookupでの結合
lookUpStage := bson.D{{Key: "$lookup", Value: bson.D{
  {Key: "from", Value: "shop"},
  {Key: "localField", Value: "shop_id"},
  {Key: "foreignField", Value: "_id"},
  {Key: "as", Value: "shop"},
}}}
// shopをunwindする
unwindStage := bson.D{{Key: "$unwind", Value: "$shop"}}
// 取得項目の指定
projectStage := bson.D{{Key: "$project", Value: bson.D{
  {Key: "_id", Value: 1},
  {Key: "name", Value: 1},
  {Key: "detail", Value: 1},
  {Key: "shop_id", Value: 1},
  {Key: "shop.name", Value: 1},
}}}
// 抽出条件
matchStage := bson.D{{Key: "$match", Value: bson.D{{Key: "$or", Value: bson.A{
  bson.M{"name": bson.D{{Key: "$regex", Value: primitive.Regex{Pattern: "検索ワード", Options: "i"}}}},
  bson.M{"shop.name": bson.D{{Key: "$regex", Value: primitive.Regex{Pattern: "検索ワード", Options: "i"}}}},
}}}}}

// クエリの実行
pipeLine := mongo.Pipeline{lookupStage, unwindStage, projectStage, matchStage}
cur, err := col.Aggregate(context.Background(), pipeLine)
// 結果のデコード処理は省略・・

좋은 웹페이지 즐겨찾기