Reputation: 5826
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
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
Reputation: 5600
You can use this query.
db.collection.aggregate([
{ $unwind: "$books" },
{
$match: {
"books.title": { $exists: true},
}
}
])
Upvotes: 0
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
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