简体   繁体   中英

How do you only select MongoDB documents that have a sub-field, using the aggregation framework?

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.

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?

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