簡體   English   中英

如何在 MongoDB.Driver C# 的深度嵌套數組中檢查值是否存在?

[英]How check value existence in a deeply nested array in MongoDB.Driver C#?

如下圖,集合為Posts 帖子和評論的_id是已知的。

那么,如何檢查給定值d是否存在於AgreedUserIds中?

在此處輸入圖像描述

試試這個進行單字符搜索:

db.Posts.find(
    {
        _id: "b4d5...ff79",
        Comments: {
            $elemMatch: {
                _id: "c1ea...d45",
                AgreedUserIds: "d"
            }
        }
    }
);

這用於多字符搜索:

db.Posts.find(
    {
        _id: "b4d5...ff79",
        Comments: {
            $elemMatch: {
                _id: "c1ea...d45",
                AgreedUserIds: { $in: ["c", "d"] }
            }
        }
    }
);

如果你想保留它BsonDocument你可以選擇像這樣組合過濾器>

var client = new MongoClient();
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("posts");
var postId = new BsonObjectId(new ObjectId("604b5ff389ff6887d1b91a93"));
var commentId = new BsonObjectId(new ObjectId("604b5ff389ff6887d1b91a92"));
var userId = "a";
//var userId = "e"; // not found
var postIdMatches = Builders<BsonDocument>.Filter.Eq("_id", postId);
var commentIdMatches = Builders<BsonDocument>.Filter.Eq("_id", commentId);
var userIdInside = Builders<BsonDocument>.Filter.AnyEq("AgreedUserIds", userId); // "a" in checking
var commentCheck = Builders<BsonDocument>.Filter.ElemMatch("Comments", userIdInside & commentIdMatches); // & combines filters. Also ElemMatch on any of the Comments is passing the criteria
var rows = (await collection.FindAsync<BsonDocument>(postIdMatches & commentCheck)).ToList(); 

您還可以GetCollection<Post>與 C# Post class 描述郵政業務 object,並使用。任何 Z7FB58B61118DFE38B666Z 查詢。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM