Node.js 如何在Mongo中根据函数的结果进行排序?
我正在MEAN stack中开发一个web应用程序(我的后端代码在NodeJS服务器中运行),用于注册我的网络资产。我的数据库中有Node.js 如何在Mongo中根据函数的结果进行排序?,node.js,mongodb,Node.js,Mongodb,我正在MEAN stack中开发一个web应用程序(我的后端代码在NodeJS服务器中运行),用于注册我的网络资产。我的数据库中有数据集合,其中包括一些条目。每个条目的一个字段是ip字段。我的最终目标是按IP排序 ip字段值是字符串。如果我使用排序({ip:1}),我将遇到以下问题:ip为192.168.1.145的条目将出现在ip为192.168.1.2的条目之前,因为比较会逐位进行 所以,为了克服这个问题,我想用192.168.001.145和192.168.001.002这样的形式来转换每
数据
集合,其中包括一些条目。每个条目的一个字段是ip
字段。我的最终目标是按IP排序
ip
字段值是字符串。如果我使用排序({ip:1})
,我将遇到以下问题:ip为192.168.1.145的条目将出现在ip为192.168.1.2的条目之前,因为比较会逐位进行
所以,为了克服这个问题,我想用192.168.001.145和192.168.001.002这样的形式来转换每个IP。我希望此转换仅在排序过程中进行,并避免添加另一个字段,或仅将该格式的数据保存在IP字段中
到目前为止,我已经:
//------------ Get all entries, sorted by IP ------------
router.get('/getEntriesSortedByIP', (req, res, next) => {
db.get().collection('data')
.find()
.sort(function(u) {
if (u.ip != '') {
let ip_part = u.ip.split('.');
while (ip_part[0].length < 3) {
ip_part[0] = '0' + ip_part[0];
}
while (ip_part[1].length < 3) {
ip_part[1] = '0' + ip_part[1];
}
while (ip_part[2].length < 3) {
ip_part[2] = '0' + ip_part[2];
}
while (ip_part[3].length < 3) {
ip_part[3] = '0' + ip_part[3];
}
u.ip = ip_part[0] + '.' + ip_part[1] + '.' + ip_part[2] + '.' + ip_part[3];
}
return u;
})
.toArray((err, data) => {
if (err) { return res.send(err) }
res.json(data);
});
});
/-----------获取所有条目,按IP排序------------
router.get('/GetEntriessOrtedByp',(请求、恢复、下一步)=>{
db.get().collection('data')
.find()
.sort(函数(u){
如果(u.ip!=''){
让ip_部分=u.ip.分割('.');
而(ip_部分[0]。长度<3){
ip_部分[0]=“0”+ip_部分[0];
}
而(ip_部分[1]。长度<3){
ip_部分[1]=“0”+ip_部分[1];
}
而(ip_部分[2]。长度<3){
ip_部分[2]=“0”+ip_部分[2];
}
而(ip_部分[3]。长度<3){
ip_部分[3]=“0”+ip_部分[3];
}
u、 ip=ip_部分[0]+'.+ip_部分[1]+'.+ip_部分[2]+'.+ip_部分[3];
}
返回u;
})
.toArray((错误,数据)=>{
if(err){return res.send(err)}
res.json(数据);
});
});
改造是成功的。唯一的问题是排序没有发生
有什么想法吗?谢谢 MonogBD解决方案如何: 将
ip
字段拆分为4个临时字段。我们将字符串
转换为整数
。现在我们按时间变量排序。最后,使用$unset
我们从结果临时变量中删除
db.collection.aggregate([
{
$addFields: {
ip1: {
$toInt: {
$arrayElemAt: [
{
$split: [
"$ip",
"."
]
},
0
]
}
},
ip2: {
$toInt: {
$arrayElemAt: [
{
$split: [
"$ip",
"."
]
},
1
]
}
},
ip3: {
$toInt: {
$arrayElemAt: [
{
$split: [
"$ip",
"."
]
},
2
]
}
},
ip4: {
$toInt: {
$arrayElemAt: [
{
$split: [
"$ip",
"."
]
},
3
]
}
}
}
},
{
$sort: {
ip1: 1,
ip2: 1,
ip3: 1,
ip4: 1
}
},
{
$unset: [
"ip1",
"ip2",
"ip3",
"ip4"
]
}
])
如果要进行客户端排序,请在
数据数组中调用排序。它仅适用于3个新字段。如果我添加第四个新字段,则不会进行排序。为什么会发生这种情况?更新:出于某种原因,它只适用于{$split:[“$ip”,““]},1
,{$split:[“$ip”,““]},2
和{$split:[“$ip”,“]},3
。当我使用{$split:[“$ip”,““]},0
时,数据不会返回。为什么会发生这种情况?@kostas_me________________________________?