1

文字列、別のサブドキュメント、ネストされた別のサブドキュメントなど、さまざまなタイプが含まれる場合がある MongoDB のサブドキュメントがあります。タイプに関係なく、このサブドキュメントのコンテンツ内を検索するクエリを作成しようとしています。

次のドキュメントが与えられます。

{ name: "test1", content: "test contents"}
{ name: "test2", content: {family: "tests family content", last: "another test content"} }
{ name: "test3", content: {subdocument: {family: "super family contents", last: "last test content"} } }

すべてのドキュメントとサブドキュメント内のすべての文字列を検索するクエリを使用したいと考えています。すでに次のクエリを試しましたが、サブドキュメントの最もネストされたレベルのみを返します - content.subdocument.family:

{ $or: [
    {"content": {'$regex': '.*conten.*', '$options': 'i'}},
    {"content.family": {'$regex': '.*conten.*', '$options': 'i'}},
    {"content.last": {'$regex': '.*conten.*', '$options': 'i'}},
    {"content.subdocument.family": {'$regex': '.*conten.*', '$options': 'i'}},
    {"content.subdocument.last": {'$regex': '.*conten.*', '$options': 'i'}}
]}

ネストされたすべての文字列を一度に反復処理する 1 つのクエリを作成することは可能ですか?

4

1 に答える 1

0

$orここでは、 inの構文がありません$regex。次のように$orを使用する必要があります。

db.collection.find({
    $or: [{
    "content": {
        '$regex': '.*conten.*',
        '$options': 'i'
    }
    }, {
    "content.family": {
        '$regex': '.*conten.*',
        '$options': 'i'
    }
    }, {
    "content.last": {
        '$regex': '.*conten.*',
        '$options': 'i'
    }
    }, {
    "content.subdocument.family": {
        '$regex': '.*conten.*',
        '$options': 'i'
    }
    }, {
    "content.subdocument.last": {
        '$regex': '.*conten.*',
        '$options': 'i'
    }
    }]
})

編集:

上記のクエリでは、次の結果が得られます。

[{
    "_id": ObjectId("55f41b6aef4766c946112a2d"),
    "name": "test1",
    "content": "test contents"
}, {
    "_id": ObjectId("55f41b6aef4766c946112a2e"),
    "name": "test2",
    "content": {
    "family": "tests family content",
    "last": "another test content"
    }
}, {
    "_id": ObjectId("55f41b6aef4766c946112a2f"),
    "name": "test3",
    "content": {
    "subdocument": {
        "family": "super family contents",
        "last": "last test content"
    }
    }
}]
于 2015-09-12T12:38:36.697 に答える