node.js - mongoose如何同时查询多个字段的多种值

查看:114
本文介绍了node.js - mongoose如何同时查询多个字段的多种值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

查询网上的手册,都是一些简单的例子,不懂怎样写才能达到下面的需求。

模型是这样的

  msgid: { type: 'string' }, //消息ID
  time: { type: 'string' },
  push: { type: 'number'}, //是否推送消息 1是 0否
  val: {
    id: { type: 'string' },
    username: { type: 'string' },
    avatar: { type: 'string' }, 
    content: { type: 'string' },
    type: { type: 'string', default: 'friend' },
    toid: { type: 'string' },
    toname: { type: 'string' }
  }

msgid的值可能是 123-222 , 222-456 这样的。 - 两头是两个用户的id值
我想查询
push为1的值 同时 msgid 中包含222的id,无论在前在后。
按time排序。
只返回val中的数据。

解决方案

db.data.find({"push":1,"msgid":{"$regex":"[.-222|222-.]+","$options":"i"}},{"val":1}).sort({"time":1})

$regex为正则匹配里面可以写正则表达式,"$options":"i"不区分大小写
find的第二个参数为需要返回的字段1表示返回,0标识不返回
sort {"time":1} 1 按照time正序,-1 按照time倒序

这篇关于node.js - mongoose如何同时查询多个字段的多种值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆