[英]how to find the distinct values of a field in a MongoDB collection using Node MongoClient
In my MEAN application, I need to find the distinct values of a field named "DataFields" from my collection "Fixed_Asset_Register", using (non-mangoose) MongoClient: 在我的MEAN应用程序中,我需要使用(非芒果)MongoClient从我的集合“Fixed_Asset_Register”中找到名为“DataFields”的字段的不同值:
var mongodb = require('mongodb');
var assert = require('assert');
var MongoClient = mongodb.MongoClient;
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
var collection = db.collection('Fixed_Asset_Register');
var distictDataFieldsValue = ?
}
What is the proper syntax to get back the distinct values of the field named "DataFields"? 获取名为“DataFields”的字段的不同值的正确语法是什么?
I solved this issue using collection.distinct : 我使用collection.distinct解决了这个问题:
collection.distinct("DataFields",(function(err, docs){
console.log(docs);
assert.equal(null, err);
db.close();
}))
You could also do this by way of aggregation framework . 您也可以通过聚合框架来完成此操作。 The suitable aggregation pipeline would consist of the $group
operator stage which groups the document by the DataFields
key and create an aggregated field count
which stores the documents produced by this grouping. 合适的聚合管道将由$group
运算符阶段组成,该阶段通过DataFields
键对文档进行分组,并创建聚合字段count
,该count
存储由此分组生成的文档。 The accumulator operator for this is $sum
. 累加器运算符为$sum
。
The next pipeline stage would be the $match
operator which then filters the documents having a count
of 1 to depict distinction. 下一个管道阶段将是$match
运算符,然后过滤具有count
1的文档以描述区别。
The last pipeline operator $group
then group those distinct elements and adds them to a list by way of $push
operator. 最后一个管道运算符$group
然后将这些不同的元素分组,并通过$push
运算符将它们添加到列表中。
In the end your aggregation would look like this: 最后,您的聚合将如下所示:
var collection = db.collection('Fixed_Asset_Register'),
pipeline = [
{
"$group": {
"_id": "$DataFields",
"count": {"$sum": 1}
}
},
{
"$match": { "count": 1 }
},
{
"$group": {
"_id": 0,
"distinct": { "$push": "$_id" }
}
}],
result = collection.aggregate(pipeline).toArray(),
distictDataFieldsValue = result[0].distinct;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.