Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 451
RoyHB Avatar asked Aug 13 '15 12:08

RoyHB


People also ask

How do I search for a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What is the mongo command to find all documents that match search criteria?

To find documents that match a set of selection criteria, call find() with the <criteria> parameter. MongoDB provides various query operators to specify the criteria.

How do I use wildcard search in MongoDB?

Create a Wildcard Index on All Fields With this wildcard index, MongoDB indexes all fields for each document in the collection. If a given field is a nested document or array, the wildcard index recurses into the document/array and stores the value for all fields in the document/array.

What does $all do in MongoDB?

The $all operator selects the documents where the value of a field is an array that contains all the specified elements.


1 Answers

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)
like image 75
RoyHB Avatar answered Nov 15 '22 10:11

RoyHB