2017-03-25 1 views
0

다음과 같은 Room 개체의 구조가 있습니다. 메시지는 다음과 같은 구조 나 객실의 컬렉션의 메시지로 검색 쿼리를 수행 할주어진 필드로 중첩 된 개체의 배열을 검색하십시오.

type Message struct { 
Id  bson.ObjectId `json:"id" bson:"_id,omitempty"` 
Text  string   `json:"text" bson:"text"` 
Author  Author   `json:"author" bson:"author"` 
CreatedOn time.Time `json:"createdon" bson:"created_on"` 
Reply  []Message `json:"reply" bson:"reply,omitempty"`} 

를 가지고 객체의 중첩 배열 인

type Room struct { 
Id   bson.ObjectId  `json:"id" bson:"_id,omitempty"` 
Title  string    `json:"title" bson:"title"` 
Description string    `json:"description" bson:"description,omitempty"` 
Type  string    `json:"type" bson:"type,omitempty"` 
AdminId  bson.ObjectId  `json:"admin_id" bson:"admin_id"` 
CreatedOn time.Time   `json:"created_on" bson:"created_on"` 
Messages []Message   `json:"messages" bson:"messages,omitempty"`} 

. 나는 "$in"을 사용하여 시도했지만 도움이되지 못했습니다.

또한 값을 일치시켜 요소를 검색해야합니다. bson 정규식을 사용하여이 작업을 수행 할 수 있습니다.

&bson.RegEx{Pattern: textToFind, Options: "i"} 

는 합산 나는 객실 문서의 중첩 된 객체의 Text 필드를 기준으로 메시지를 검색해야합니다.

P. 가능한 실수로 유감스럽게도, 영어는 제 모국어가 아닙니다.

UPDATE

기본적으로, 일부 문자열을 포함 주어진 방에있는 모든 메시지를 찾고 싶어요. 예를 들어 방의 모든 메시지 (채팅)에서 'some text'하위 문자열이 포함 된 'A'를 검색합니다.

+0

당신은'collection.Find (bson.M { "messages.text"및 bson.RegEx {패턴 :와 textToFind, 옵션 : "I"}}) 같은 것을 시도 할 수있다' – Veeram

+0

@Veeram 나는 시도했다 하지만 작동하지 않습니다. –

답변

1

아래의 mongo shell aggregation 파이프 라인을 사용해보십시오.

$match 일부 객실 속성 (예 : _id).

$unwind 메시지 (변형 messages 개체로 변환)가 방안에 있습니다.

$match 입력 정규식에서 text 필드를 messages으로 필터링합니다.

$group 메시지 개체는 messages 배열로 되돌아갑니다.

$project_id을 제외하고 출력하려면 messages 만 포함하십시오.

아래는 테스트되지 않은 mgo와 같습니다.

match1 := bson.M{ 
    "$match": bson.M{ 
     "_id": roomid, 
    }, 
} 

unwind := bson.M{ 
    "$unwind": "$messages", 
} 

match2 := bson.M{ 
    "$match": bson.M{"messages.text": &bson.RegEx{Pattern: textToFind, Options: "i"}}, 
} 

group := bson.M{ 
    "$group": bson.M{ 
     "_id": null, 
     "messages": bson.M{ 
      "$push": "$messages", 
     }, 
    }, 
} 

project := bson.M{ 
    "$project": bson.M{ 
     "_id": 0, 
     "messages":1, 
    }, 
} 

all := []bson.M{match1, unwind, match2, group, project} 
pipe := collection.Pipe(all) 

result := []bson.M{} 
err := pipe.All(&result) 
+0

매우 감사합니다! 실제로 작동한다! –

관련 문제