RoyHB
RoyHB

Reputation: 1725

mongo find all with field that is object having a specified key

A mongo db has documents that look like:

{
    "_id":  : ObjectId("55cb43e8c78b04f43f2eb503"),
    <some fields>
    "topics": {
        "test/23/result": 149823788,
        "test/27/result": 147862733,
        "input/misc/test": 14672882
    }
}

I need to find all documents that have a topics field that contains a particular key. i.e. find all documents that have a topics.key = "test/27/result"

I've tried a number of things but none work yet, neither attempt below work, they return no records event though some should match:

db.collName.find({"topics.test/27/result": {$exists:true}});
db.collName.find({"topics.test\/27\/result": {$exists:true}});

How can I make the query work?

The slash characters are inserted by another process. They are mqtt topic names.

Upvotes: 8

Views: 4888

Answers (1)

RoyHB
RoyHB

Reputation: 1725

I found the solution to my problem:

I was building the query wrong in my code. In the example below, evtData.source contains the key name to search for, i.e. 'test/27/result'

The query methodology that works for me is:

var query = {};
query['topics.' + evtData.source] = {$exists: true};
db.collName.find(query)

Upvotes: 2

Related Questions