ptheofan
ptheofan

Reputation: 2270

PHP MongoDb, find all referenced documents when collection is indexed array

I have the following structure in mongo

{
    "_id": ObjectId("5188deba4c2c989909000000"),
        "_type": {
            "0": "Model_Discs"
        }
    },
    "title": "really cool cd",
    "referencedBy": {
         "0": {
           "$ref": "discs",
           "$id": ObjectId("4e171cade3a9f23359e98552") 
        },
         "1": {
           "$ref": "discs",
           "$id": ObjectId("5045c3222b0a82ec46000000") 
        } 
    }
}

This is actually an indexed array that holds references to other documents. I to find all the documents that have a reference to ObjectId("5045c3222b0a82ec46000000"). At first I wrote "referencedBy.1.$id": ObjectId("5045c3222b0a82ec46000000") which doesn't work (as expected) because the ObjectId can be found under different index in other documents i.e.

referencedBy.1.$id
referencedBy.5.$id
referencedBy.3.$id

So I need to find all documents that reference my ObjectId who are anywhere under the referencedBy DocumentSet. Something like

"referencedBy.*.$id": ObjectId("5045c3222b0a82ec46000000")

Upvotes: 0

Views: 546

Answers (1)

Derick
Derick

Reputation: 36784

I don't quite see why you have such a complicated structure. Particularily the "0" and "1" keys are problematic, especially dealing with PHP as it doesn't really like arrays with numerical string keys. The $ref/$id fields come from MongoDBRef, which should avoid as they don't provide you with any functionality.

You should just have:

{
    "_id": ObjectId("5188deba4c2c989909000000"),
    "_type": "Model_Discs",
    "title": "really cool cd",
    "referencedBy": [
        ObjectId("4e171cade3a9f23359e98552"),
        ObjectId("5045c3222b0a82ec46000000") 
    ]
}

Then you can simply query with:

db.collection.find( { referencedBy: new ObjectId("5045c3222b0a82ec46000000") } );

Upvotes: 1

Related Questions