mongoDB管道--数组查询

2022/2/19 19:11:48

本文主要是介绍mongoDB管道--数组查询,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1. 初始化数据

db.createCollection("t_demo")

db.t_demo.insertMany([
{num:[1,2,3], obj: [{name: "zhang1", age: 12}, {name: "li1", age: 13}]},
{num:[1,2], obj: [{name: "zhang2", age: 12}, {name: "li2", age: 13}]},
{num:[1,], obj: [{name: "zhang3", age: 14}, {name: "li2", age: 15}]},
])

2. 基本数据类型查询

  • in 数组中匹配到任意一个
  • all 数组中要包含所有

1. 查询包含1或者2

db.t_demo.aggregate([{
$match: {
    num: {$in: [1,2]}
}
}])

查出3条数据

/* 1 */
{
  "_id" : ObjectId("6210a06d13adc55355d6495f"),
  "num" : [1, 2, 3],
  "obj" : [{
      "name" : "zhang1",
      "age" : 12
    }, {
      "name" : "li1",
      "age" : 13
    }]
}

/* 2 */
{
  "_id" : ObjectId("6210a06d13adc55355d64960"),
  "num" : [1, 2],
  "obj" : [{
      "name" : "zhang2",
      "age" : 12
    }, {
      "name" : "li2",
      "age" : 13
    }]
}

/* 3 */
{
  "_id" : ObjectId("6210a06d13adc55355d64961"),
  "num" : [1],
  "obj" : [{
      "name" : "zhang3",
      "age" : 14
    }, {
      "name" : "li2",
      "age" : 15
    }]
}

2. 查询包含1和2

db.t_demo.aggregate([{
$match: {
    num: {$all: [1,2]}
}
}])

结果2条数据

/* 1 */
{
  "_id" : ObjectId("6210a06d13adc55355d6495f"),
  "num" : [1, 2, 3],
  "obj" : [{
      "name" : "zhang1",
      "age" : 12
    }, {
      "name" : "li1",
      "age" : 13
    }]
}

/* 2 */
{
  "_id" : ObjectId("6210a06d13adc55355d64960"),
  "num" : [1, 2],
  "obj" : [{
      "name" : "zhang2",
      "age" : 12
    }, {
      "name" : "li2",
      "age" : 13
    }]
}

3. 查询等于1和2

这里不使用$eq的原因是: $eq要保证顺序也要一致 [1,2][2,1]是不相等的

db.t_demo.aggregate([{
$match: {
    num: {$all: [1,2]},
    num: {$size: 2}
}
}])

结果1条

/* 1 */
{
  "_id" : ObjectId("6210a06d13adc55355d64960"),
  "num" : [1, 2],
  "obj" : [{
      "name" : "zhang2",
      "age" : 12
    }, {
      "name" : "li2",
      "age" : 13
    }]
}

3. 对象类型查询

通过$elemMatch或者数组名.属性名进行查询

# $elemMatch
db.t_demo.aggregate([{
$match: {
    obj: {$elemMatch: {age:12}}
}
}])

db.t_demo.aggregate([{
$match: {
    obj: {$elemMatch: {name: "zhang1", age: 12}}
}
}])

# 数组.
db.t_demo.aggregate([{
$match: {
    "obj.age": 12
}
}])

db.t_demo.aggregate([{
$match: {
    "obj.name": "zhang1",
    "obj.age": 12
}
}])


这篇关于mongoDB管道--数组查询的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程