问题描述
查询网上的手册,都是一些简单的例子,不懂怎样写才能达到下面的需求。
模型是这样的
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中的数据。
问题解答
回答1: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倒序