MongoDB arrays search

1

Hi, I've been looking for information for a couple of days to be able to do this search

  

Search the books written by 2 authors

I'll capture you how it's stored in my MongoDB

I get used to the idea that "author" is an array and there must be some possible way to tell the statement find "author".count() = 2

But I can not find anything ...

Any help is welcome!

    
asked by PictorGames 06.02.2017 в 18:27
source

1 answer

2

You can use the all operator to get documents that include all the elements of the array.

  

Select documents as long as the field in question has all the values of the array.

db.collections.books.find({
  author: {
    $all: [ 'author1', 'author2']
  }
});

If you use mongoose :

Book.find({
  author: {
    $all: [ 'author1', 'author2']
  }
});

Update

  

I want you to show me the books written by 2 authors (that the author array contains 2 records)

In that case you can add the operator $size to:

  • The array contains the authors to match
  • The array contains a size of the number of authors

Example:

Book.find({
  author: {
    $all: [ 'author1', 'author2'],
    $size: 2
  }
});

The above is translated to: "Find all the books that are written only by X and Y author" .

    
answered by 06.02.2017 / 21:28
source