databasemongodbmongodb-querymongo-collection

MongoDB - How to retrieve only one specific document from a collection


I have created a database called "Cars" and a collection inside it as, "Cars_info". I have inserted 8 documents inside it as follows.

db.Cars_info.insertMany([
  { car_id: "c1", Company: "Toyota", Model: "Aqua", Year: 2020, Price_in_usd: 25000, Category: "High-end", Country: "Japan" },
  { car_id: "c2", Company: "Toyota", Model: "Premio", Year: 2019, Price_in_usd: 35000, Category: "High-end", Country: "Japan" },
  { car_id: "c3", Company: "Audi", Model: "A6", Year: 2020, Price_in_usd: 55000, Category: "High-end", Country: "Germany" },
  { car_id: "c4", Company: "Tata", Model: "Nano", Year: 2015, Price_in_usd: 10000, Category: "Low-end", Country: "India" },
  { car_id: "c5", Company: "Volkswagen", Model: "Taos", Year: 2022, Price_in_usd: 35000, Category: "High-end", Country: "Germany" },
  { car_id: "c6", Company: "Ford", Model: "Figo", Year: 2019, Price_in_usd: 26000, Category: "High-end", Country: "America" },
  { car_id: "c7", Company: "Mahindra", Model: "Thar", Year: 2018, Price_in_usd: 18000, Category: "Low-end", Country: "India" },
  { car_id: "c8", Company: "Honda", Model: "Vezel", Year: 2015, Price_in_usd: 33000, Category: "High-end", Country: "Japan" }
])

Here I want to retrieve only the third document from the collection. But without matching any field value. like,

db.Cars_info.find({"car_id":"c3"}).pretty()

Is there any way to do this?


Solution

  • You need .skip() and .limit().

    Take the document by starting index: 2 and with only 1 document, which is the third document.

    Update: Thanks and credit to @Wernfried for pointing out, you need .sort() to guarantee to get the nth of the document. For your scenario, you have to sort by car_id.

    Sort Consistency

    MongoDB does not store documents in a collection in a particular order. When sorting on a field that contains duplicate values, documents containing those values may be returned in any order.

    db.Cars_info.find()
      .sort({ "car_id": 1 })
      .skip(2)
      .limit(1)
    

    enter image description here