Leonardo
Leonardo

Reputation: 11387

MongoDB - query for field inside array

Here's a snapshot of my document: enter image description here

I would like to know how can i retrieve only the documents where ANY of the breakout items has a property named source.

I tried the following: db.getCollection('receipts').find({"sizeBreakout.packBreackout.breakout.source":{"$exists":true}})
but a empty result is being returned always... why?!? what is the correct syntax for this query?!? Edit1:
Attached File: https://drive.google.com/file/d/0B2zKseaQl2gnVlFWZFlaRzloMDg/view?usp=sharing

Upvotes: 0

Views: 94

Answers (1)

Saleem
Saleem

Reputation: 8978

Well, if you have MongoDB 3.2, you can use this simple query.

MongoDB version 3.2+

db.docs.find({$filter: {input: "$sizeBreakout.packBreackout.breakout", 
  as: breakout,
  cond:{$exists:{"$$breakout.source": true}}}})

MongoDB version < 3.2

db.docs.aggregate([
{$unwind: "$sizeBreakout.packBreakout.breakout"},
{$match: {"sizeBreakout.packBreakout.breakout.source":{$exists: true}}}
])

This query will find all documents where sizeBreakout.packBreackout.breakout.source exists.

Upvotes: 1

Related Questions