简体   繁体   中英

Find document matching to all the provided parameters in mongodb

Suppose I have documents in collection bookDetails,

doc1: {'bookData':{'bookName':'lotr','bookPart':'Part 3'}, 'library_name':'omega','libraryId':12166}

doc2: {'bookData':{'bookName':'hp','bookPart':'Part 7'}, 'library_name':'omega','libraryId':12199}

doc3: {'bookData':{'bookName':'hertu','bookPart':'Part 7'}, 'library_name':'omega','libraryId':9999}

I want to fetch only document which matches with all fields library name: omega, library id: 12199 and bookName: hp.

For this I tried as:

await collection.aggregate([{ $match: { library_name: 'omega' } }, ]).exec();{ $match: { libraryId: 12199 } }

But I also want to match with bookname: 'hp', so I can get required document.

If anyone needs any further information please let me know.

Demo - https://mongoplayground.net/p/C2EP96CkIRo

db.collection.find({
  library_name: "omega",
  libraryId: 12199,
  "bookData.bookName": "hp"
})

Demo - https://mongoplayground.net/p/9mf9Sp8C4u6

With aggregation

db.collection.aggregate([
  {
    $match: {
      library_name: "omega",
      libraryId: 12199,
      "bookData.bookName": "hp"
    }
  }
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM