0

How do I filter out documents from a mongo collection that don't have a sub field, when using aggregation?

The collection looks like this:

{ 
  "_id": ObjectId("adasdasd"),
  "obj": { "a": 1 }
},

{ 
  "_id": ObjectId("ergergerg"),
  "obj": { "b": 2 }
},

{ 
  "_id": ObjectId("adasdasd"),
  "obj": { "a": 3, "b": 4 }
},

How would I use the aggregate() function to only select documents where the "obj" field contains the "b" subfield? The result should look like this:

{ 
  "_id": ObjectId("ergergerg"),
  "obj": { "b": 2 }
},

{ 
  "_id": ObjectId("adasdasd"),
  "obj": { "a": 3, "b": 4 }
},

I realize that I can use find() and $exists, But I am looking for a solution using aggregate(). Any help is greatly appreciated.

Tom Mathew
  • 144
  • 1
  • 11

1 Answers1

1

Off the top of my head:

$match: {'obj.b': { $exists: true, $ne: null } }

Take a look at the $match stage:

Filters the documents to pass only the documents that match the specified condition(s) to the next pipeline stage.

The $match stage has the following prototype form:

{ $match: { } }

And the $exists operator:

$exists Syntax: { field: { $exists: } }

When is true, $exists matches the documents that contain the field, including documents where the field value is null. If is false, the query returns only the documents that do not contain the field.

Related question: How do you query for "is not null" in Mongo?

arielnmz
  • 8,354
  • 9
  • 38
  • 66
  • Yes this is what I was looking for. Turns out, I was using $limit before $match and wasn't getting any results. Thank you! – Tom Mathew Jun 27 '19 at 19:58