简体   繁体   中英

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. ie 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.

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, ie 'test/27/result'

The query methodology that works for me is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM