Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to get all value for a field in MongoDB & Node.js

So I'm really new to MongoDB and document storage stuffs. I'm having a hard time trying to find the most elegant and efficient solution to do the following:

I have a collection called tests. In each tests there are actions with a field owner. See below:

{
"_id" : ObjectId("528c731a810761651c00000f"),
"actions" : [
    {
        "action" : "6784",
        "owner" : "MERCHAND_1",
        "_id" : ObjectId("528c7292810761651c00000e")
    },
    {
        "action" : "1",
        "owner" : "MERCHAND_1",
        "_id" : ObjectId("528c7292810761651c00000d")
    },
    {
        "action" : "1358",
        "owner" : "MERCHAND_2",
        "_id" : ObjectId("528c7292810761651c00000c")
    }
],
"name" : "Test 1",
"product" : ObjectId("528bc4b3a0f5430812000010")

}

How can I have a list (array) of each distinct owner value using Node.js & MongoDB (I'm using mongoose driver). Is it better to do it on mongoside or node.js side? If for example I run the function on the previous table, it should return:

[
    {
      "owner":"MERCHAND_1"
    },
    {
      "owner":"MERCHAND_2"
    }
]
like image 627
Alex Grs Avatar asked Nov 21 '13 14:11

Alex Grs


People also ask

How do I capture a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

How get all items from MongoDB?

Fetch all data from the collection If we want to fetch all documents from the collection the following mongodb command can be used : >db. userdetails. find(); or >db.

Is count faster than find MongoDB?

find({}). count() more fast then collection.


2 Answers

MongoDB supports a distinct command to do this. You can use dot notation to target fields within arrays as in this case. In the shell:

db.test.distinct('actions.owner')

outputs:

[
  "MERCHAND_1",
  "MERCHAND_2"
]
like image 165
JohnnyHK Avatar answered Nov 15 '22 09:11

JohnnyHK


You can do this with MongoDB using the command

db.runCommand({
  distinct: 'tests',
  key: 'actions.owner'
});

which gives you

{
  "values" : [
    "MERCHAND_1",
    "MERCHAND_2"
  ],
  "stats" : {...},
  "ok" : 1
}

This will include every document in the tests collection. If, however, you wanted to just check a single document, you could re-write the command as

db.runCommand({
  distinct: 'tests',
  key: 'actions.owner',
  query: { _id: ObjectId("528c731a810761651c00000f") }
});
like image 31
Travis Avatar answered Nov 15 '22 09:11

Travis