0
 I have this data:

> db.Category.find().pretty()
{
    "_id" : ObjectId("542450a928db034349fb3bf2"),
    "name" : "A category",
    "products" : [
        {
            "_id" : ObjectId("542450a928db034349fb3bf3"),
            "name" : "Producto de categoria",
            "price" : 11.11
        }
    ]
}

When I run db.Category.find( {}, {products:1} ) I get this:

{ "_id" : ObjectId("542450a928db034349fb3bf2"), "products" : [ { "_id" : ObjectId("542450a928db034349fb3bf3"), "name" : "Producto de categoria", "price" : 11.11 } ] }

I get the data about one product, but how can I get the data about all products?

2
  • Your example document only has 1 product. Not sure if I understand what you are looking to get back? Commented Sep 26, 2014 at 13:23
  • @JamesWahlin yes, but imagine I have more products, I want to fetch all them without giving a number, because I don't know exactly how many are there.
    – tirenweb
    Commented Sep 26, 2014 at 13:25

2 Answers 2

1

If you had multiple documents containing products, you could retrieve all as follows by capturing the query cursor and iterating over the set:

replset:PRIMARY> var cur = db.Category.find( {}, {products:1} );
replset:PRIMARY> while (cur.hasNext()) {
... var doc = cur.next();
... printjson(doc);
... }
{
    "_id" : ObjectId("542450a928db034349fb3bf2"),
    "products" : [
        {
            "_id" : ObjectId("542450a928db034349fb3bf3"),
            "name" : "Producto de categoria",
            "price" : 11.11
        }
    ]
}

If you have multiple products within the "products" array then you would iterate over the array contained in each result document.

0

Your NoSql statment seems correct. You have only one embbeded documnent of products that's why you got only one.

db.Category.find( {}, {products:1} )

Or you can use

db.Category.find({products:1})

Don't get confuse with "products:1", it is a projection that you want products. Here Projection is of type { field1: <boolean>, field2: <boolean> ... }. Fields that you want to include explicitly in you querying data use like "products:1" otherwise for excluding use "products:0".

You can refer this link: enter link description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.