本文介绍了MongoDb-查询数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
基于MongoDB文档 https://docs.mongodb.com/manual /tutorial/query-arrays/
Based on the MongoDB documentation https://docs.mongodb.com/manual/tutorial/query-arrays/
我有这个收藏集:
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
{ item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);
这些查询是否等效?
db.inventory.find( { tags: { $all: ["red"] } } )
和
db.inventory.find( { tags: "red" } )
如果它们有不同的用途,什么时候代替另一个使用?
If they have different purposes , when to use one instead of the other?
推荐答案
是的,这两个查询是等效的.您仅在使用 $all
要查询包含多个tags
值的文档:
Yes, those two queries are equivalent. You would only use $all
when you want to query for the docs containing multiple tags
values:
db.inventory.find( { tags: { $all: ["red", "blank"] } } )
此查询将匹配示例集合中除最后一个文档以外的所有文档.
This query would match all but the last document in your example collection.
这篇关于MongoDb-查询数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!