1

I have a mongo document as follows i want to be able to do make two searches:

1) search for id= 123 2) serach for id= 1234

So the document i need could be the top level or nested.

{
   "id": "123",
   "name" : "testName",
   "docs": [
   {
   "id": "1234",
   "name" : "testName4",
   "docs": []
    }
   ]
}

So basically i could need the top document or the nested document. Im looking at graph lookup but i dont think that will do what i need, i also looked at aggregates - seems like they would work?

1
  • 1
    You can have good reference over here Commented Feb 28, 2019 at 10:22

1 Answer 1

2

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!

Sign up to request clarification or add additional context in comments.

2 Comments

If you don't know your Database format before, you can use a mapReduce() query to execute JavaScript-Code serverside and display the results as you wish. However, this is not very performant, so I would recommend you to solve your Problem by a different Database-Scheme, where you can predict nestings.
@user1555190 please review my edit as it fits your needs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.