[MongodB] 추출 조건에 룩업과 결합된 목표를 포함하는 컬렉션 라이브러리
개요
기존[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"`
}
이번 구상 키워드 검색은 item
의name
또는 shops
의name
와 일치하는 문서를 추출합니다.샘플
룩업으로 결합한 후 샵
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)
// 結果のデコード処理は省略・・
Reference
이 문제에 관하여([MongodB] 추출 조건에 룩업과 결합된 목표를 포함하는 컬렉션 라이브러리), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/someone7140/articles/b585f47f426a4b텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)