夢のの夢
夢のの夢

Reputation: 5826

MongoDB how to find all elements in an array exist a field?

I came across a query that I couldn't make. The use case I was told is that I would need to find if there is any faulty data where a book doesn't contain a title. Books happen to be a array. So I need to find out if all books in the books array must contain a title field.

I have only came up with the query for the first element like so {"books": {$exists: true, $not: {$size: 0}}, "books.0.title": {$exists: false}}. How do I do it for all elements?

Document:

{
  id: oid(abc123..)
  name: John Doe
  books: [
    {
      title: MyBook1
    }
    {
      title: MyBook2
    }
    ...
  ]
}

Upvotes: 0

Views: 1716

Answers (4)

Khaled Osman
Khaled Osman

Reputation: 1467

you can use dot notation for querying mongodb, so you can try something like this

Books.find({ 'books.title': {$ne: null}})

Upvotes: 1

Ankit Kumar Rajpoot
Ankit Kumar Rajpoot

Reputation: 5600

You can use this query.

db.collection.aggregate([
  { $unwind: "$books" },
  {
    $match: {
        "books.title": { $exists: true},
    }
  }
])

Upvotes: 0

Matt Oestreich
Matt Oestreich

Reputation: 8528

You can use an aggregation for this..

You can check out an example query here showing you how this works.

db.collection.aggregate([
  { $unwind: "$books" },
  {
    $match: {
      $or: [
        { "books.title": { $exists: true, $eq: "" }},
        { "books.title": { $exists: true, $eq: null }}
      ]
    }
  }
])

Upvotes: 1

Ashok
Ashok

Reputation: 2932

You can use this query

db.getCollection("books").find({
  $expr: {
    $eq: [
      { $size: "$books" },
      {
        $size: {
          $filter: {
            input: "$books",
            cond: { $ne: ["$$this.title", undefined] }
          }
        }
      }
    ]
  }
});

or

db.getCollection("books").find({
  $expr: {
    $allElementsTrue: {
      $map: { input: "$books", in: { $ne: ["$$this.title", undefined] } }
    }
  }
});

Upvotes: 1

Related Questions