2017-03-25 6 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.S.間違いの可能性があり申し訳ありませんが、英語は母国語ではありません。

UPDATE

基本的に、私はいくつかの部分文字列を含んで与えられた部屋内のすべてのメッセージを見つけたいです。たとえば、ルーム内のすべてのメッセージ(チャット)の 'A'(一部のテキスト部分文字列を含む)を検索します。

+0

あなたは 'collection.Find(bson.M { "messages.text":&bson.RegEx {パターン:textToFind、オプション: "I"}})のような何かを試すことができます' – Veeram

+0

@Veeram私が試してみましたそれは動作しません。 –

答えて

1

以下のmongoシェル集約パイプラインを試すことができます。

$matchいくつかの部屋の属性(ex _id)です。

$unwind客室内のメッセージ(変換messagesの配列に変換)。

$match入力正規表現textに対してフィールドmessagesと入力します。

$group sメッセージオブジェクトはmessagesアレイに戻ります。

$project_idを除外し、出力にはmessagesのみを含めます。

db.collection.aggregate(
{$match:{"_id":roomid}}, 
{$unwind:"$messages"}, 
{$match:{"messages.text": { $regex: /textToFind/i } }}, 
{$group:{_id:null,messages:{$push:"$messages"}}}, 
{$project:{_id:0, messages:1}}) 

以下は、試験されていない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

非常にマッチしていただきありがとうございます!それは実際に動作します! –

関連する問題