Can you clarify, what your results should look like?
If you want to search for documents which have an id of "123" or contain a document in "docs" with the id "1234" you could simply query for:
db.teststack.find({$or: [{"id": "123"}, {"docs.id": "1234"}]})
which will always return the complete document.
EDIT
See this example I've written:
db.teststack.mapReduce(
function(){
let scanfunction = (passobj) => {
if(passobj.id === "123") {
emit("id123", this._id);
}
else {
for(var key in passobj) {
if(typeof passobj[key] === "object"){
scanfunction(passobj[key]);
}
}
}
}
scanfunction(this);
}
,
function(key, stuff){
let ret = "";
for(let t1 in stuff)
ret += stuff[t1] + ";";
return ret;
}
,
{
"out": "keys"
}
).find()
It simply returns a string containing all ObjectIds which
- a: have the id: "123"
- b: contain a document with id: "123"
- c: contain a document containing a doc.... of which at least one has the id: "123"
The Code is scalable, as it scans all keys of all documents in your database, but therefore it is not performant!