【问题】mongoose 如何多条件查询,包括同时查询数组?
发布于 6 年前 作者 lisniuse 5983 次浏览 来自 问答

我的需求:我想查找_id 为 5b35fdfeea0b0221640b2039 并且数组 starPropertys 里包含了 5b35fdffea0b0221640b203b 的数据

我有一个集合符合条件,它这样的:

{
    "_id": "5b35fdfeea0b0221640b2039",
    "power": [],
    "score": 0,
    "starPropertys": [
        "5b35fdffea0b0221640b203b",
        "5b35fe07ea0b0221640b203d"
    ],
    "active": true,
    "email": "test12@qq.com",
    "password": "$2a$10$PoTkIE0WyVHvSnUGH60hNeHQIw1UWUvvpaN3ra4/v49tw87e1GJ1m",
    "createTime": 1530265086887,
    "updateTime": 1530265086887,
    "__v": 0,
    "nickname": "jack ma"
}

我的查询语句如下:

this.ctx.model.Col.findOne({
  $and: [
	  {
		  _id: userId,
	  },
	  {
		  "starPropertys": propertyId
	  }
  ]
}).exec();

然而并没有查到任何数据,我想请问如何实现我这样的需求?

5 回复

你的 mongo 版本是多少? 我这里亲测是可以的 1530266390946.jpg

你可以不用 $and , 用下面的方法 :

db.getCollection('users').find({_id:'5b35fdfeea0b0221640b2039',starPropertys:'5b35fdffea0b0221640b203b'})

1530266536604.jpg

我想到问题原因了

mongo 默认的 _idObjectId() 我不清楚题主 this.ctx.model.Col.findOne 这个方法是哪个模块的 , 所以不妨试一下 在查询条件里面 加上 ObjectId

this.ctx.model.Col.findOne({
  $and: [
	  {
		  _id: ObjectId('5b35fdfeea0b0221640b2039'),
	  },
	  {
		  "starPropertys": "5b35fdffea0b0221640b203b"
	  }
  ]
}).exec();

或者是

this.ctx.model.Col.findOne({_id:ObjectId('5b35fdfeea0b0221640b2039'),starPropertys:'5b35fdffea0b0221640b203b'}}).exec();

如果mongo里面存的不是字符串而是ObjectId,查的时候需要ObjectId包一下。另外这种查询不需要and,楼上写的方式就行。

来自✨ Node.js开源项目精选

@CRAZYFAKE 可以了,是我别的地方代码写错了。

回到顶部