Gibs LeFleur
Gibs LeFleur

Reputation: 131

Searching Inside Mongo Array

Here is my mongo Structure:

{
  "_id": "QEvgJKERy5xGNLv7J",
  "title": "test 2",
  "owner": "HQNGYZvrrdQRwLNvT",
  "markdown": "sdfasdfdasf adsfadsfasdf",
  "state": "Draft",
  "category": [
    "Bios & Memoirs",
    "Classics"
  ],
  "type": "Article",
  "lastupdate": "",
  "slug": "test-2",
  "date": 1504890635515,
  "views": "0",
  "rating": "0",
  "username": "gibigbig"
}

I would like to find all articles based on category. So something like:

db.documents.find({category: 'Comedy'});

but it doesn't work. Any help is greatly appreciated.

Upvotes: 0

Views: 51

Answers (2)

Michel Floyd
Michel Floyd

Reputation: 20227

Since category is an array you can also use $in:

db.documents.find({ category: { $in: ['Comedy'] }});

It seems backwards since you're looking for the value Comedy inside the array but that's the way the syntax is defined. You can also perform a many-to-many match, i.e.

db.documents.find({ category: { $in: ['Comedy','Tragedy'] }});

or you can just do a straight up single-value search as you discovered:

db.documents.find({category: 'Comedy'});

Upvotes: 2

Gibs LeFleur
Gibs LeFleur

Reputation: 131

db.documents.find({category: 'Comedy'}); My environment was off. Fixed and these queries now work.

Upvotes: 0

Related Questions