The most efficient way to get all the value for a field in MongoDB & Node.js

So, I'm really new to MongoDB and document storage. I find it difficult to find the most elegant and effective solution to do the following:

I have a collection called tests. In each test, there are actions with the owner of the field. 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 get a list (array) of each individual owner value using Node.js and MongoDB (I use the mongoose driver). Is it better to do this on the Mongozide or on the Node.js side? If, for example, I ran a function in the previous table, it should return:

 [ { "owner":"MERCHAND_1" }, { "owner":"MERCHAND_2" } ] 
+6
source share
2 answers

You can do this with MongoDB with 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 just wanted to check one document, you could rewrite the command as

 db.runCommand({ distinct: 'tests', key: 'actions.owner', query: { _id: ObjectId("528c731a810761651c00000f") } }); 
+7
source

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

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

outputs:

 [ "MERCHAND_1", "MERCHAND_2" ] 
+11
source

Source: https://habr.com/ru/post/958567/


All Articles