How to search all elements of an array in Mongodb

Asked

Viewed 641 times

-1

I have a Mongodb document as an example:

{
  "_id": "andresm",
  "username": "Andre Salesmo",
  "carros": [
    {"marca": "ferrari", "tipo": "coupe", "preco": "850000.00", "data_compra": "22/01/2015", "modelo": "512TR"},
    {"marca": "nissan", "tipo": "coupe", "preco": "542000.00", "data_compra": "12/05/2018", "modelo": "GTR"},
  ]
}

I would like to know how I can do a search filtering by id and returning all cars. I am using pymongo as a driver and I was trying in the following way and I did not get result:

cursor = mongo.db.movimentacoes.find(
 {"_id": usrId, "carros": {} }
  • Managed to make it work?

1 answer

0

There is an error in your query. In this case the method find receives only one parameter, one object, and will use it to query. As it is, Mongo is looking for a document with the past id and in which cars is an empty object.

Change to mongo.db.movimentacoes.find({"_id": usrId}) (or only mongo.db.movimentacoes.find(usrId), to do an ID search).

If your goal is to return only carros, add one more parameter to the method with {"carros": 1}, ex: mongo.db.movimentacoes.find({"_id": usrId}, {"carros": 1}).

Note that Mongo implicitly returns the ID. To change this behavior it is necessary to delete with {_id: 0}, getting mongo.db.movimentacoes.find({"_id": usrId}, {"carros": 1, _id: 0}).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.