How do I query mongodb with MID
I have query something as SQL's like query:
select * from users where MID(nama,1,2)='A'
How to do the same in mongodb? I can't find a operator for like in the documentation.
Try the following aggregation query:
db.users.aggregate([{$project: { _id: 0, name: { $substr: [ "$name", 0, 1 ]}}}])
This uses the projections and substring: https://docs.mongodb.com/v3.2/reference/operator/aggregation/project/ https://docs.mongodb.com/v3.2/reference/operator/aggregation/substr/
For example:
> db.dropDatabase()
{ "dropped" : "test", "ok" : 1 }
> db.users.save({"name": "Kevin"})
WriteResult({ "nInserted" : 1 })
> db.users.save({"name": "Matt"})
WriteResult({ "nInserted" : 1 })
> db.users.save({"name": "Sakis"})
WriteResult({ "nInserted" : 1 })
> db.users.save({"name": "Lee"})
WriteResult({ "nInserted" : 1 })
>
> db.users.aggregate([{$project: { _id: 0, name: { $substr: [ "$name", 0, 1 ]}}}])
{ "name" : "K" }
{ "name" : "M" }
{ "name" : "S" }
{ "name" : "L" }
链接地址: http://www.djcxy.com/p/86408.html
上一篇: 面向对象的NoSQL与文档不同
下一篇: 如何用MID查询mongodb