gpt4 book ai didi

mongodb - 何时在 mongodb 中使用 $and 查询

转载 作者:可可西里 更新时间:2023-11-01 10:44:34 25 4
gpt4 key购买 nike

谁能告诉我这两个查询之间的区别?

db.foo.find({ $and: [{a: 1}, {a: {$gt: 5}}]})

db.foo.find({a:1, a:{$gt:5}})

编辑好的,让我稍微改变一下问题。假设如下

dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })
dev(mongod-2.2.0)>db.foo.insert({UserID: 1, Status:'unread' })

我想查找用户 id 1 的所有未读消息。我要这样做吗

db.foo.find({UserID:1, Status:'unread'})

或者这个

db.foo.find({$and: [{UserID:1},{Status:'unread']})

最佳答案

使用$和,查询时会同时考虑这两个条件。如果没有 $and,查询中只会考虑 a 的最后一个规范。这似乎也发生在从 mongo shell 插入时。

在您编辑的问题中,我肯定会使用 db.foo.find({UserID:1, Status:'unread'})

示例如下:

> db.sotest.insert({a : 1})
> db.sotest.insert({a : 2})
> db.sotest.insert({a : 6})
> db.sotest.insert({a : 7})
> db.sotest.insert({a : [1, 7]})
> db.sotest.find()
{ "_id" : ObjectId("50587c0164433af6a99c988f"), "a" : 1 }
{ "_id" : ObjectId("50587c0564433af6a99c9890"), "a" : 2 }
{ "_id" : ObjectId("50587c0d64433af6a99c9891"), "a" : 6 }
{ "_id" : ObjectId("50587c1064433af6a99c9892"), "a" : 7 }
{ "_id" : ObjectId("50587c1f64433af6a99c9893"), "a" : [ 1, 7 ] }
> db.sotest.find({a:1, a:{$gt:5}})
{ "_id" : ObjectId("50587c0d64433af6a99c9891"), "a" : 6 }
{ "_id" : ObjectId("50587c1064433af6a99c9892"), "a" : 7 }
{ "_id" : ObjectId("50587c1f64433af6a99c9893"), "a" : [ 1, 7 ] }
> db.sotest.find({a:{$gt:5}, a:1})
{ "_id" : ObjectId("50587c0164433af6a99c988f"), "a" : 1 }
{ "_id" : ObjectId("50587c1f64433af6a99c9893"), "a" : [ 1, 7 ] }
> db.sotest.find({$and : [{a:{$gt:5}}, {a:1}]})
{ "_id" : ObjectId("50587c1f64433af6a99c9893"), "a" : [ 1, 7 ] }
>

关于mongodb - 何时在 mongodb 中使用 $and 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12478014/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com