MongoDB
 sql >> Baza danych >  >> NoSQL >> MongoDB

W MongoDB, jak wykonać zapytanie na podstawie tego, czy jedno pole tekstowe zawiera inne?

Możesz to zrobić za pomocą $where tworząc RegExp dla string1 a następnie przetestować go z string2 :

db.test.find({$where: 'RegExp(this.string1).test(this.string2)'})

Jeśli jednak korzystasz z MongoDB 3.4+, możesz to zrobić wydajniej, korzystając z $indexOfCP operator agregacji:

db.test.aggregate([
    // Project  the index of where string1 appears in string2, along with the original doc.
    {$project: {foundIndex: {$indexOfCP: ['$string2', '$string1']}, doc: '$$ROOT'}},
    // Filter out the docs where the string wasn't found
    {$match: {foundIndex: {$ne: -1}}},
    // Promote the original doc back to the root
    {$replaceRoot: {newRoot: '$doc'}}
])

Lub bardziej bezpośrednio, używając także $redact :

db.test.aggregate([
    {$redact: {
        $cond: {
            if: { $eq: [{$indexOfCP: ['$string2', '$string1']}, -1]},
            then: '$$PRUNE',
            else: '$$KEEP'
        }
    }}
])



  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Bezagentowe monitorowanie bazy danych za pomocą ClusterControl

  2. Wyjątek limitu czasu kursora Mongo

  3. Jak zastosować ograniczenia w MongoDB?

  4. Podłączanie MongoDB z aplikacji mobilnej lub przeglądarkowej

  5. Jak mogę połączyć się z mongodb za pomocą ekspresu bez mangusty?